Redis cache and spring cache

http://120.79.167.88:4444/articles/2019/05/12/1557661499842.html

Record the difference between Redis cache and spring cache
1.Redis is a third-party cache, so the cache data still exists after the project is restarted
2. Spring cache is built on the JVM for caching, so the cache will disappear automatically after the project is started.

Business: the expiration time needs to be set in the case of email verification code and SMS verification code.
How to use: use Redis and SpringCache.
Expiration time: if you need to set the expiration time, you need to use redis. If you do not need to set the expiration time, redis and SpringCache can both.

How to use SpringCache:

1. Use @ EnableCaching in the startup class

@SpringBootApplication
@EnableCaching //Start spring cache cache
public class GatheringApplication {}

2. Use @ Cacheable when adding cache

//Store cache
@Cacheable(value = "gathering",key = "#id")
public Gathering findById(String id){}3.Use when you need to delete the cache@CacheEvict
//delete
@CacheEvict(value = "gathering",key = "#gathering.id")
public void update(Gathering gathering){}


Here are some usage methods of SpringDataRedis:

/**
   * Parameter 1: key parameter 2: value parameter 3: time parameter 4: time unit
   */
redisTemplate.opsForValue().set(REDIS_ARTICLE_KEY+"_"+id,article,10, TimeUnit.SECONDS);

stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//Save data to redis and set cache time

stringRedisTemplate.opsForValue().get("test")//Get val in cache according to key
stringRedisTemplate.boundValueOps("test").increment(-1);//val do - 1 operation
stringRedisTemplate.boundValueOps("test").increment(1);//val +1
stringRedisTemplate.getExpire("test")//Get expiration time according to key
stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//Get the expiration time according to the key and convert it to the specified unit
stringRedisTemplate.delete("test");//Delete cache according to key
stringRedisTemplate.hasKey("546545");//Check whether the key exists and return the boolean value
stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//Set expiration time
stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//Store the set set set in the specified key
stringRedisTemplate.opsForSet().isMember("red_123", "1")//Check whether the specified data exists in the collection according to the key
stringRedisTemplate.opsForSet().members("red_123");//Get set set set according to key


 

Keywords: Redis Spring jvm

Added by tabs on Tue, 12 Nov 2019 22:35:20 +0200