阿里 jetcache 使用说明

·  阅读 260

简介

jar包封装了缓存的基础使用,比直接使用spring-cache更加灵活,还封装了分布式锁的快速使用,总之对于缓存的使用更加方便了。

版本引入

注意版本问题,jedis的jar包可能会冲突

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.5.4</version>
        </dependency>
        <dependency>
            <groupId>com.alicp.jetcache</groupId>
            <artifactId>jetcache-starter-redis</artifactId>
            <version>2.6.2</version>
        </dependency>
复制代码

yml配置

普通使用,只需要更改redis的地址和密码即可

jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: linkedhashmap
      keyConvertor: fastjson
      limit: 100
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: 192.168.137.100
      port: 6379
      password: huzhihui
复制代码

使用案例

  • 创建基础对象(必须序列化)
public class User implements Serializable {

    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
复制代码
  • 缓存方法的返回值
@Service
public class UserService {

    @Cached(expire = 20, cacheType = CacheType.REMOTE)
    @CacheRefresh(refresh = 20)
    public User getById(Long id){
        User user = new User();
        user.setId(id);
        user.setName(id+"name");
        return user;
    }
}
复制代码
  • 对象缓存
@CreateCache(name = "user_cache",expire = 20, cacheType = CacheType.BOTH, localLimit = 50)
    private Cache<Long, User> userCache;

    @Autowired
    private UserService userService;

    public UserController() {
    }

    @GetMapping("getById")
    public Object getById(Long id){
        User user = userService.getById(id);
        userCache.computeIfAbsent(id,a -> userService.getById(id));
        return user;
    }
复制代码
  • 分布式锁
@CreateCache(name = "user_cache",expire = 20, cacheType = CacheType.BOTH, localLimit = 50)
    private Cache<Long, User> userCache;

    @Autowired
    private UserService userService;

    public UserController() {
    }

    @GetMapping("getById")
    public Object getById(Long id){
        User user = userService.getById(id);
        boolean result = userCache.tryLockAndRun(id+4L,60, TimeUnit.SECONDS,()->{
            try {
                Thread.sleep(10000);
                System.out.println("ceshi ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(result);
        return user;
    }
复制代码

image.png

分类:
后端
收藏成功!
已添加到「」, 点击更改