SpringBoot集成redis + spring cache
Spring Cache集成redis的运行原理:
Spring缓存抽象模块通过CacheManager来创建、管理实际缓存组件,当SpringBoot应用程序引入spring-boot-starter-data-redi依赖后吗,容器中将注册的是CacheManager实例RedisCacheManager对象,RedisCacheManager来负责创建RedisCache作为缓存管理组件,由RedisCache操作redis服务器实现缓存数据操作。实际测试发现默认注入的RedisCacheManager操作缓存用的是RedisTemplate<Object, Object>,因此我们需要自定义cacheManager,替换掉默认的序列化器。
实现代码:
添加mybatis和redis依赖:

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

添加mapper映射:

1 @Mapper
2 public interface ProductMapper {
3 @Select("select * from tb_product where product_id=#{id}")
4 Product getProductById(Long id);
5
6 @Update("update tb_product set product_name=#{productName},product_desc=#{productDesc} WHERE product_id=#{productId}")
7 int updateProduct(Product product);
8
9 @Delete("delete from tb_product where product_id=#{id}")
10 void deleteProductById(Long id);
11
12 @Select("select * from tb_product where product_name=#{productName}")
13 Product getProductByName(String productName);
14 }

Service:

1 package com.sl.cache.service;
2 import com.sl.cache.entity.Product;
3 import com.sl.cache.mapper.ProductMapper;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.cache.annotation.CacheConfig;
6 import org.springframework.cache.annotation.CacheEvict;
7 import org.springframework.cache.annotation.CachePut;
8 import org.springframework.cache.annotation.Cacheable;
9 import org.springframework.cache.annotation.Caching;
10 import org.springframework.stereotype.Service;
11
12 @Service
13 @CacheConfig(cacheNames = "product")
14 public class ProductService {
15 @Autowired
16 private ProductMapper productMapper;
17
18 @Cacheable(cacheNames = "product1",key = "#root.methodName+'['+#id+']'")
19 //@Cacheable(cacheNames = {"product1","product2"})// 默认key为参数,多个参数SimpleKey [arg1,arg2]
20 //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'")
21 //@Cacheable(cacheNames = "product",keyGenerator = "myKeyGenerator")
22 //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'",condition="#a0>10",unless = "#a0==11") //或者condition="#id>10")
23 public Product getProductById(Long id){
24 Product product =productMapper.getProductById(id);
25 System.out.println(product);
26 return product;
27 }
28
29 @CachePut(value="product",key = "#result.productId",condition = "#result!=null")
30 public Product updateProduct(Product product){
31 int count = productMapper.updateProduct(product);
32 System.out.println("影响行数:"+count);
33 if(count>0){
34 return product;
35 }else{
36 return null;
37 }
38 }
39
40 //@CacheEvict(value="product",key="#id")
41 //@CacheEvict(value="product",allEntries = true) //清楚所有缓存
42 @CacheEvict(value="product",allEntries = true,beforeInvocation = true) //清楚所有缓存
43 public boolean deleteProductById(Long id) {
44 productMapper.deleteProductById(id);
45 return true;
46 }
47
48 //含有CachePut注解,所以执行这个方法时一定会查询数据库,及时有cacheable注解
49 @Caching(
50 cacheable = {@Cacheable(value="product",key="#productName")},
51 put = {
52 @CachePut(value="product",key="#result.productId"),
53 @CachePut(value="product",key="#result.productName")
54 }
55 )
56 public Product getProductByName(String productName){
57
58 Product product =productMapper.getProductByName(productName);
59
60 return product;
61 }
62 }

Controller:

package com.sl.cache.controller;
import com.sl.cache.entity.Product;
import com.sl.cache.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
public class ProductController { @Autowired
private ProductService productService; @GetMapping("/product/{id}")
public Product getProduct(@PathVariable("id") Long id) { Product product = productService.getProductById(id);
return product;
} //prooduct?productid=1&productName= &
@GetMapping("/product")
public Product updateProduct(Product product) {
productService.updateProduct(product);
return product;
} @GetMapping("/delproduct")
public String delProduct(@RequestParam(value="id") Long id) { productService.deleteProductById(id);
return "ok";
} @GetMapping("/product/name/{productName}")
public Product getEmpByLastName(@PathVariable("productName") String productName){
return productService.getProductByName(productName);
}
}

自定义cacheManager实现:

1 package com.sl.cache.config;
2 import com.sl.cache.entity.Product;
3 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
4 import org.springframework.cache.CacheManager;
5 import org.springframework.cache.config.CacheManagementConfigUtils;
6 import org.springframework.context.annotation.Bean;
7 import org.springframework.context.annotation.Configuration;
8 import org.springframework.context.annotation.Primary;
9 import org.springframework.data.redis.cache.RedisCacheConfiguration;
10 import org.springframework.data.redis.cache.RedisCacheManager;
11 import org.springframework.data.redis.cache.RedisCacheWriter;
12 import org.springframework.data.redis.connection.RedisConnectionFactory;
13 import org.springframework.data.redis.core.RedisTemplate;
14 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
15 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
16 import org.springframework.data.redis.serializer.RedisSerializationContext;
17 import org.springframework.data.redis.serializer.RedisSerializer;
18 import org.springframework.data.redis.serializer.StringRedisSerializer;
19
20 import java.net.UnknownHostException;
21 import java.time.Duration;
22
23 @Configuration
24 public class MyRedisConfig {
25
26 @Bean(name = "redisTemplate")
27 public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
28
29 RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
30
31 redisTemplate.setConnectionFactory(redisConnectionFactory);
32 redisTemplate.setKeySerializer(keySerializer());
33 redisTemplate.setHashKeySerializer(keySerializer());
34 redisTemplate.setValueSerializer(valueSerializer());
35 redisTemplate.setHashValueSerializer(valueSerializer());
36 return redisTemplate;
37 }
38
39 @Primary
40 @Bean
41 public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
42 //缓存配置对象
43 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
44
45 redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间:30分钟
46 .disableCachingNullValues() //如果是空值,不缓存
47 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) //设置key序列化器
48 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); //设置value序列化器
49
50 return RedisCacheManager
51 .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
52 .cacheDefaults(redisCacheConfiguration).build();
53 }
54 private RedisSerializer<String> keySerializer() {
55 return new StringRedisSerializer();
56 }
57
58 private RedisSerializer<Object> valueSerializer() {
59 return new GenericJackson2JsonRedisSerializer();
60 }
61 }

启用缓存,添加mybatis Mapper映射扫描:

1 @MapperScan("com.sl.cache.mapper")
2 @SpringBootApplication
3 @EnableCaching
4 public class SpringbootCacheApplication {
5
6 public static void main(String[] args) {
7 SpringApplication.run(SpringbootCacheApplication.class, args);
8
9 }
10 }

SpringBoot集成redis + spring cache的更多相关文章
- springBoot集成Redis遇到的坑(择库)源码分析为什么择库失败
提示: springboot提供了一套链接redis的api,也就是个jar包,用到的连接类叫做LettuceConnectionConfiguration,所以我们引入pom时是这样的 <de ...
- SpringBoot集成Redis 一 分布式锁 与 缓存
1.添加依赖及配置(application.yml) <!-- 引入redis依赖 --> <dependency> <groupId>org.springfram ...
- 【springBoot】springBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- SpringBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- springboot集成redis(mybatis、分布式session)
安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...
- Windows环境下springboot集成redis的安装与使用
一,redis安装 首先我们需要下载Windows版本的redis压缩包地址如下: https://github.com/MicrosoftArchive/redis/releases 连接打开后如下 ...
- SpringBoot | 集成Redis
Windows下安装: https://github.com/MicrosoftArchive/redis/releases zip下就解包到自定义目录下,msi就跟着步骤安装 进入安装目录下运行命令 ...
- springboot集成redis使用redis作为session报错ClassNotFoundException类RememberMeServices
springboot 集成redis使用redis作为缓存,会报错的问题. 错误信息: java.lang.IllegalStateException: Error processing condit ...
- SpringBoot集成Redis实现缓存处理(Spring AOP实现)
第一章 需求分析 计划在Team的开源项目里加入Redis实现缓存处理,因为业务功能已经实现了一部分,通过写Redis工具类,然后引用,改动量较大,而且不可以实现解耦合,所以想到了Spring框架的A ...
随机推荐
- hdu5988(费用流,对数相乘做加法)
题意:一个网络流的图,有n个点,从1~n,然后m条边,每个点有两个值,一个是人的数量si一个是饭的数量bi.每条m边有容量ci,还有走上去可能踩断电线的概率pi(第一次踩上去没有事,之后都要p概率). ...
- ASP.NET中调用百度地图API
1.打开链接http://developer.baidu.com/map/jshome.htm这里有很多DEMO,或者你直接百度搜索“百度地图API”,第一个就是.进入后有很多方向供你选择,由于现在开 ...
- iOS SDK开发之 .framework静态库
查看.a静态库的生成及使用单击此处 注:这篇教程将只使用一小部分Objective-C代码,本文主要讲解从开始到应用的详细步骤.环境:xcode 9.2下面我们开始操作: 第一步:创建一个静态库工程 ...
- JS调用服务器端方法
javascript函数中执行C#代码中的函数:方法一:1.首先建立一个按钮,在后台将调用或处理的内容写入button_click中; 2.在前台写一个js函数,内容为document. ...
- 用U盘完成win10系统的安装
电脑太卡了,每次都要重装,然后每次忘记要从哪里开始动手,都要百度,仅以此篇记录下 目录 1.系统盘准备 2.从U盘启动安装 1.系统盘准备 第一步:在电脑中完成系统盘制作工具的安装,由于它是要依赖.n ...
- Oracle11g数据文件DBF迁移
最近接手了一个以前同事遗留下来的项目,时机比较敏感,因为要召开11届全国少数名族运动会.建国70周年,以及香港暴乱,其中网站上挂载有十几个系统的入口链接,不巧的是其中一个系统存在若口令,被公安部安全局 ...
- LeetCode算法题-Rectangle Overlap(Java实现)
这是悦乐书的第325次更新,第348篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第195题(顺位题号是836).矩形表示为数组[x1,y1,x2,y2],其中(x1,y ...
- Scratch少儿编程系列:(三)第一个例子 潜水员
一. 选择背景 在上一节系统界面的介绍中,选择"6角色"的左边,点击"从背景库中选择背景". 选择主题水下中的"underwater3". ...
- win10安装Tensorflow1.9GPU版本
前言 看到DateWhale出了一篇安装教程(微信公众号DateWhale),决定体验一下Tensorflow1.9的GPU版本..其实一开始装的是2.0,但是tf.Session()就报错了,说是2 ...
- docker安装Rancher
docker安装Rancher //拉取镜像 docker pull rancher:v2.0.4 //运行容器 docker run -d -p : -p : --restart=always -- ...