SpringBoot 集成Redis +SpringCache做缓存
一.给user加缓存
1.首先创建springboot-redis-cache模块,并把springboot-restful-api的内容复制过来。
2.修改三层架构,即加service层
添加service.UserService接口,再创建实现类service.impl.UserServiceimpl,记得实现类要加上@Service注解。并实现user的增删改查功能。同时将Controller的调用改成UserService。
3.加入redis cache pool等依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
4.配置redis
server:
port: 8090
# 扫描mapper.xml文件
mybatis:
mapper-locations:
- classpath:mapping/*.xml
spring:
application:
name: springboot-ssm
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123zxc
redis:
host: 127.0.0.1
port: 6379
password: 123zxc
database: 0
lettuce:
pool:
max-active: 32
max-wait: 300ms
max-idle: 16
min-idle: 8
5.启动类加上@EnableCaching注解
6.Service加缓存
@Service
public class UserServiceImpl implements UserService {
private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Resource
private UserMapper userMapper;
@Override
@Cacheable(value = "user:id",key = "#id")
public User getOneUser(int id) {
logger.info("get one go mysql ...");
return userMapper.selectByPrimaryKey(id);
}
@Cacheable(value = "user:list")
@Override
public List<User> findAll() {
logger.info("find all go mysql ...");
return userMapper.list();
}
@CacheEvict(value = "user:list",allEntries = true)
@Override
public int add(User user) {
return userMapper.insert(user);
}
@Caching(
evict = {
@CacheEvict(value = "user:id", key = "#user.id"),
@CacheEvict(value = "user:list", allEntries = true)
}
)
@Override
public int update(User user) {
return userMapper.updateByPrimaryKey(user);
}
@Caching(
evict = {
@CacheEvict(value = "user:id", key = "#id"),
@CacheEvict(value = "user:list", allEntries = true)
}
)
@Override
public int delete(int id) {
return delete(id);
}
}
以上SpringBoot默认对redis 的配置,如果我们想修改redis的配置,如序列化方式、默认过期时间等等。则需要我们创建RedisConfig.java配置类。
二.手动配置RedisConfig.java
具体配置如下,其中一个是操作redis 的RedisTemplate,一个是缓存使用的CacheManager,其中修改了序列化方式,所以要把原来的缓存清空。
@Component
@Configuration
@ConfigurationProperties("spring.cache.redis")
public class RedisConfig extends CachingConfigurerSupport {
private Duration timeToLive = Duration.ofMinutes(30);
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
//RedisTemplate配置
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
//配置事务
template.setEnableTransactionSupport(true);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
二.SpringBoot如何操作Redis
Springboot 操作redis引入的依赖可以不用引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
1.说明
SpringBoot Redis提供一个强大的模版操作redis,它就是RedisTemplate,使用它可以很方便的操作redis 的五大数据类型。下面我们写一个测试类使用RedisTemplate的相关API。
首先把引入spring-boot-starter-test依赖,同时去掉junit依赖,否则会报错!
2.添加RedisTemplateTest
在test/java/xyz.java1024 下创建RedisTemplateTest测试类,加上@RunWith(SpringRunner.class)
@SpringBootTest(classes = RedisApp.class)注解,指定启动类作用是读取配置信息。具体代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RedisApp.class)
public class RedisTemplateTest {
@Resource
private RedisTemplate redisTemplate;
/**
*
* 介绍 如何使用 redisTemplate 操作String List Set ZSet Hash五种数据类型
* 本测试只 使用了部分常用的 api,如在集合等复杂数据类型 有更多的api 实现更加强大的功能,查阅相关文档即可!
*
*/
/**
* String 类型set
*/
@Test
public void testSet() {
redisTemplate.opsForValue().set("test","this is test");
}
/**
* String 类型get
*/
@Test
public void testGet() {
Object test = redisTemplate.opsForValue().get("test");
System.out.println("test = " + test);
}
/**
* 添加元素
*/
@Test
public void testLSet() {
redisTemplate.opsForList().leftPush("testList","testList1");
}
/**
* 获取List 的所有元素
*/
@Test
public void testLGet() {
List testList = redisTemplate.opsForList().range("testList", 0, -1);
System.out.println("testList = " + testList);
}
/**
* Set类型 set
*/
@Test
public void testSSet() {
redisTemplate.opsForSet().add("testSet","testSet1");
}
/**
* Set 类型get
*/
@Test
public void testSGet() {
Set testSet = redisTemplate.opsForSet().members("testSet");
System.out.println("testSet = " + testSet);
}
/**
* hash set
*/
@Test
public void testHSet() {
redisTemplate.opsForHash().put("testHash","value1","key1");
redisTemplate.opsForHash().put("testHash","value2","key2");
}
/**
* hash get
*/
@Test
public void testHget() {
Object o = redisTemplate.opsForHash().get("testHash", "value1");
System.out.println("o = " + o);
}
/**
* Zset set
*/
@Test
public void testZSet() {
redisTemplate.opsForZSet().add("java1024","SpringBoot",10);
redisTemplate.opsForZSet().add("java1024","SpringCloud",3);
}
/**
* Zset get
*/
@Test
public void testZGet() {
// 正序
Set all = redisTemplate.opsForZSet().range("java1024", 0, -1);
System.out.println("all = " + all);
//反序
Set reverseRange = redisTemplate.opsForZSet().reverseRange("java1024", 0, -1);
System.out.println("reverseRange = " + reverseRange);
}
}
总结
操作Redis不依赖SpringCache,实现SpringCache也不止Redis,也可以用ehCache做缓存!只是现在主流还是用Redis做缓存。
网友评论