Learn Spring Boot: (25) Use Redis to implement data caching

foreword

Since Ehcache exists in the process of a single java program, it cannot meet the situation of multiple programs being distributed. It is necessary to centrally manage the caches of multiple servers, and a cached register is required, and Redis is used here.

text

When the application wants to read data from the cache, but the data is not found in the cache, it will re-fetch the data from the database, and then store the data in the cache.
And when we need to update or delete data in the cache, we need to invalidate the cache.

cache

configure

Add redis connection parameters to the system configuration file:

spring:
  redis:
    host: 192.168.19.200 # 120.79.208.199 # host ,默认 localhost
    port: 6379 # 端口号,默认6379
    pool:
    # 设置都是默认值,可以按需求设计
      max-active: 8 # 可用连接实例的最大数目,默认值为8;如果赋值为-1,则表示不限制;
      max-idle: 8  # 控制一个pool最多有多少个状态为idle(空闲的)的redis实例,默认值也是8。
      max-wait: -1 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
      min-idle: 0 # 控制一个pool最少有多少个状态为idle(空闲的)的redis实例,默认值为0。
    timeout: 0 # 连接超时时间 单位 ms,默认为0
    password: master # 密码,根据自己的 redis 设计,默认为空

Then add the annotation to open the cache on the system entry startup class @EnableCaching.
If no other cache is enabled, this will automatically open the redis cache.

You can also customize the registration of RedisCacheManager and set relevant parameters:

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        // 设置缓存最大时间 24 h
        redisCacheManager.setDefaultExpiration(24 * 60 * 60);
        return redisCacheManager;
    }

use

@Service
@CacheConfig(cacheNames = "em")
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDao dao;

    @Override
    @Cacheable(key = "#p0")
    public Employee findOne(Long id) {
        return dao.findOne(id);
    }

    /**
     * 更新缓存中的数据,
     * 由于 redis 是存在外部,不是 ehcache 那样存在于项目进程中,需要我们主动去更新 缓存
     * @param employee
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CachePut(key = "#p0.id")
    public Employee update(Employee employee) {
        return dao.save(employee);
    }

    /**
     * 同样主动去删除 cache
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#p0")
    public void delete(Long id) {
        dao.delete(id);
    }
}

For the use of annotations, refer to the previous study of Spring Boot: (21) Use EhCache to implement data caching

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325723997&siteId=291194637