SpringBoot Redis 2.0.x

本文详细介绍了如何在Spring Boot项目中整合Redis缓存,并通过示例展示了如何使用@Cacheable注解来缓存数据查询结果,同时配置了自定义键生成策略及Json序列化。
  • redis的安装 在笔者之前的文章中有介绍redis的安装,不会的可以去看 笔者之前写的文章redis安装
  • 完成安装后如果不熟悉redis的操作,redis官方文档也有基本操作指南,redis基本操作,如果觉得没问题了就可以开始对redis的整合
  1. maven安装依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
复制代码

redis自动会吧cache的依赖带过来,所有不用配置,如图

  1. 启动类增加@EnableCaching 注解
@SpringBootApplication
@MapperScan("com.tanoak.mapper")
@EnableCaching
public class BootRedisApplication {
	public static void main(String[] args) {
		SpringApplication.run(BootRedisApplication.class, args);
	}
}

复制代码
  1. service层增加@Cacheable 注解
@Override
	@Cacheable(cacheNames= "tea")
	public Teacher getTeaById(Integer id) {
		logger.info("进行查询实体 ID为"+id);
		return teacherMapper.getTeaById(id) ;
	}

复制代码
  1. controller 查询
@GetMapping("/tea/{id}")
public Teacher getTea(@PathVariable("id")Integer id){
		return	teacherService.getTeaById(id) ;
	}
复制代码

RedisCacheManager 配置

在SpringBoot2.x中,移除了1.x中的配置,因此要配置Json序列化与1.x的差别很大,看代码


@Configuration
@EnableCaching
public class MyRedisConfig extends CachingConfigurerSupport {

    /*
    *自定义键生成策略
    */
	@Bean
	public KeyGenerator KeyGenerator() {
		return (target, method, params) -> {
			StringBuilder sb = new StringBuilder();
			sb.append(target.getClass().getName());
			sb.append(method.getName());
			for (Object obj : params) {
				sb.append(obj.toString());
			}
			return sb.toString();
		};
	}


	@Bean
	public RedisCacheConfiguration redisCacheConfiguration() {
		Jackson2JsonRedisSerializer<Object> 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 redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
		redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
				RedisSerializationContext
						.SerializationPair
						.fromSerializer(jackson2JsonRedisSerializer)
				//设置默认超过期时间是30秒
		).entryTtl(Duration.ofMinutes(30));

		return redisCacheConfiguration;
	}

}
复制代码

![(https://upload-images.jianshu.io/upload_images/9819800-04848a258463db18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 没有打印sql,说明缓存成功,与redis集成就完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值