SpringBoot-- use Spring Cache integration redis

I. Introduction

  Spring Spring encapsulation of the Cache is cached for EHCache, Redis, Guava other cache.

Second, the role

  The main way is to use annotations to handle cache, for example, when we use redis cache, data query, if the query that will determine whether the results found in an empty, if not empty, it will result in a memory cache redis, Analyzing layer is required here; with the annotation Spring Cache processing, it is not required to judge can achieve the purpose.

  Example:

  before use:

public List<User> selectByUsernameRedis(String username) {
        String key = "user:username:"+username;
        List<User> userList = userMapper.selectByuserName(username);
        if(!userList.isEmpty()){
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(userList));
        }
        return userList;
    }

  After use:

@Cacheable(value = "user", key = "#username")
    public List<User> selectByUsernameRedis1(String username) {
        return userMapper.selectByuserName(username);
    }

 

Third, the configuration and use

  Introducing the package and profile consistent with integration alone redis, not described herein.

  1, main function increase @EnableCaching configuration, if the main function was not added @EnableCaching configuration, the following configuration is not effective.

  

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

  2, code implementation

  There are @ Cacheable, @ CachePut, @ CacheEvict three notes, correspondence is as follows:

  @Cacheable the query, the query cache, if there is a direct return; if not, query the database, the result is not empty directly into the cache.

  @CachePut cached, apply to new or updated method.

  @CacheEvict delete cache, delete suitable method.

    @CachePut(value = "user")
    @Override
    public String saveOrUpdate(User user) {
        userMapper.insert(user);
        return JSON.toJSONString(user);
    }

    @Cacheable(value = "user", key = "#id")
    @Override
    public String get(Long id) {
        return JSON.toJSONString(userMapper.selectByUserId(id));
    }

    @CacheEvict(value = "user", key = "#id")
    @Override
    public void delete(Long id) {
        userMapper.deleteByUserId(id);
    }

 

Guess you like

Origin www.cnblogs.com/liconglong/p/11698705.html