一、添加jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、修改配置
spring.cache.type=redis
三、使用
package com.drunck.service.impl;
import javax.annotation.Resource;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import com.drunck.domain.SysAdmin;
import com.drunck.mapper.SysAdminMapper;
import com.drunck.service.CacheService;
@CacheConfig(cacheNames = "ehCache")
@Repository
public class CacheServiceImpl implements CacheService {
@Resource
private SysAdminMapper sysAdminMapper;
@CachePut(key = "'key_'+#sysAdmin.getId()")
@Override
public SysAdmin save(SysAdmin sysAdmin) {
SysAdmin admin = new SysAdmin();
admin.setId(sysAdmin.getId());
admin.setUserName(sysAdmin.getUserName());
return admin;
}
@CachePut(key = "'key_'+#sysAdmin.getId()")
@Override
public SysAdmin update(SysAdmin sysAdmin) {
SysAdmin admin = new SysAdmin();
admin.setId(sysAdmin.getId());
admin.setUserName(sysAdmin.getUserName());
return admin;
}
@Cacheable(key = "'key_'+#id")
@Override
public SysAdmin queryById(String id) {
System.out.println("查询功能,缓存找不到,直接读库, id=" + id);
return sysAdminMapper.selectByPrimaryKey(id);
}
@CacheEvict(key = "'key_'+#id")
@Override
public void deleteById(String id) {
}
}
四、缓存管理器
package com.drunck.configuration;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
/**
* redis 自定义缓存管理器
*
* @author wujing
*/
@Configuration
public class RedisCacheConfiguration {
/**
* 自定义缓存管理器.
*
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// 设置默认的过期时间
cacheManager.setDefaultExpiration(20);
Map<String, Long> expires = new HashMap<String, Long>();
// 单独设置
expires.put("ehCache", 200L);
cacheManager.setExpires(expires);
return cacheManager;
}
}