SpringBoot2.x整合Redis进行数据缓存
程序员文章站
2022-07-07 11:38:04
...
SpringBoot2.x配置使用Redis
pom文件中引入:
<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>
启动类标注:@EnableCaching
application.properties:
spring.redis.host=0.0.0.0 #redis所在的服务器ip地址
SpringBoot2.x的Reids配置模板
目的:将缓存数据的Key存为String类型,Value则以json的格式存储在redis中,在读取缓存时,同样返回json格式
@Configuration
public class MyRedisConfig {
/*
SpringBoot2.x的ReidsCacheManager自定义配置方法
缓存之后,key会多一个前缀,默认是将CacheName作为key的前缀
*/
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
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()
// 缓存有效期60s
//.entryTtl(Duration.ofSeconds(60))
// 设置key序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
// 设置value序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
// 不缓存null值
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
System.out.println("ReidsCacheManager自定义配置方法被调用了...");
return cacheManager;
}
}
写一个Controller进行测试:
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
public Department getDeptById(Integer id);
}
@Service
public class DeptService {
@Resource
private DepartmentMapper departmentMapper;
@Cacheable(cacheNames = "dept")
public Department getDeptById(Integer id){
System.out.println("查询的部门是:"+id);
return departmentMapper.getDeptById(id);
}
@RestController
public class DeptController {
@Resource
private DeptService deptService;
@GetMapping("/dept/{id}")
public Department getDept(@PathVariable("id") Integer id) {
return deptService.getDeptById(id);
}
}
第一次向浏览器请求,会先从数据库查找,再将查找到的数据缓存到Redis中,我们配置了Redis的缓存格式(json),存储数据如下:
我们再向浏览器发送同一个查找请求,此时不再查找数据库,而是使用Redis中的缓存数据:
上一篇: springboot2.x中,shiro使用redis缓存
下一篇: c语言——指针与一维数组
推荐阅读
-
redis与ssm整合方法(mybatis二级缓存)
-
SpringBoot缓存详解并整合Redis架构
-
完整SpringBoot Cache整合redis缓存(二)
-
SpringBoot 整合Redis 数据库的方法
-
Laravel 下配置 Redis 让缓存、Session 各自使用不同的 Redis 数据库
-
Spring Boot 2整合Redis做缓存
-
JAVAEE——宜立方商城06:Redis安装、数据类型和持久化方案、Redis集群分析与搭建、实现缓存和同步
-
php中操作memcached缓存进行增删改查数据的实现代码
-
数据库缓存mybatis,redis
-
使用Redis和Java进行数据库缓存