Introduction to the

This JAR package encapsulates the basic use of caching, which is more flexible than using Spring-cache directly. It also encapsulates the fast use of distributed locks, which makes the use of caching more convenient.

Version to introduce

Note versioning issues, jedis JAR packages may conflict

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> < version > 2.5.4 < / version > < / dependency > < the dependency > < groupId > com. The alicp. Jetcache < / groupId > < artifactId > jetcache - starter - redis < / artifactId > < version > 2.6.2 < / version > < / dependency >Copy the code

ymlconfiguration

For common use, you only need to change the redis address and password

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
Copy the code

Use case

  • Create the base object (must be serialized)
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; }}Copy the code
  • The return value of the cache method
@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; }}Copy the code
  • Object caching
@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;
    }
Copy the code
  • A distributed lock
@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; }Copy the code