Redis cache processing


1. Redis environment construction

Set up redis service in the form of docker

    docker run ‐di ‐‐name=tensquare_redis ‐p 6379:6379 redis



Spring data redis is a part of the spring family. It provides access to redis services through simple configuration in srping applications, highly encapsulates the underlying development packages of reids (jedis, jredis, and RJC), and redistemplate provides various redis operations.


3. Implement project cache processing

 3.1 query article operation cache

(1) Introduce dependencies in the project’s pom.xml


(2) Modify application.yml and add the configuration under the spring node

(3) Modify the service, introduce redistemplate, and modify findbyid method

        private RedisTemplate redisTemplate;
*Query entity by ID
        * @param id
        * @return
        public Label findById(String id) {
//Extract from cache
          Label label=(Label)redisTemplate.opsForValue().get(“Label_”+id);
//If the cache does not exist, query the database and put it into the cache
          if(label==null) {
          label= labelDao.findById(id).get();
          redisTemplate.opsForValue().set(“label_” + id, label);
          return label;
   3.2 clear cache after modification or deletion

      * @param label
      public void update(Label label) {
redisTemplate.delete( “label_” + label.getId() );// Delete cache;
      * @param id
      public void deleteById(String id) {
redisTemplate.delete( “label_” + id );// Delete cache

   3.3 cache expiration processing

Modify the findbyid method and set the expiration time of 1 day
        redisTemplate.opsForValue().set(“label_” + id, label,1,TimeUnit.DAYS);
To facilitate testing, we can change the expiration time to 10 seconds, and then observe the console output
        redisTemplate.opsForValue().set(“label_” + id, label,10,TimeUnit.SECONDS);