springboot整合redis

springboot整合redis

注解:

 @Configuration

  @Configuration底层是含有@Component ,所以@Configuration 具有和 @Component 的作用。

  @Configuration可理解为用spring的时候xml里面的<beans>标签。

  注: 

  1) 配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。

  2) 配置类不能是 final 类(没法动态代理)。

  3) 配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类。

  4) 配置类必须是非本地的(即不能在方法中声明,不能是 private)。

  5) 任何嵌套配置类都必须声明为static。

  6) @Bean方法不能创建进一步的配置类(也就是返回的bean如果带有@Configuration,也不会被特殊处理,只会作为普通的 bean)。

   @EnableCaching

  1) @EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。

  2) 如果你使用了这个注解,那么你就不需要在XML文件中配置cache manager了。

  3) 当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。

  @Bean

  @Bean可理解为用spring的时候xml里面的<bean>标签。

  注: 

  1) @Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 

  2) @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;

  3) 既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Repository等注解注册bean(在需要注册的类上加注解),当然需要配置@ComponentScan注解进行自动扫描。

导入pom依赖

1 <dependency>
2         <groupId>org.springframework.boot</groupId>
3         <artifactId>spring-boot-starter-data-redis</artifactId>
4     </dependency>
5     <dependency>
6         <groupId>redis.clients</groupId>
7         <artifactId>jedis</artifactId>
8     </dependency>

创建RedisConfig

RedisConfig类用于Redis数据缓存。

 //继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。

  1 package com.javaqi.springboot002.config;
  2 
  3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
  4 import com.fasterxml.jackson.annotation.PropertyAccessor;
  5 import com.fasterxml.jackson.databind.ObjectMapper;
  6 import org.springframework.cache.CacheManager;
  7 import org.springframework.cache.annotation.CachingConfigurerSupport;
  8 import org.springframework.cache.annotation.EnableCaching;
  9 import org.springframework.cache.interceptor.KeyGenerator;
 10 import org.springframework.context.annotation.Bean;
 11 import org.springframework.context.annotation.Configuration;
 12 import org.springframework.data.redis.cache.RedisCacheConfiguration;
 13 import org.springframework.data.redis.cache.RedisCacheManager;
 14 import org.springframework.data.redis.connection.RedisConnectionFactory;
 15 import org.springframework.data.redis.core.RedisTemplate;
 16 import org.springframework.data.redis.core.StringRedisTemplate;
 17 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 18 import org.springframework.data.redis.serializer.StringRedisSerializer;
 19 
 20 import java.lang.reflect.Method;
 21 import java.time.Duration;
 22 import java.util.HashMap;
 23 import java.util.HashSet;
 24 import java.util.Map;
 25 import java.util.Set;
 26 
 27 /**
 28  * redis配置类
 29  **/
 30 @Configuration
 31 @EnableCaching//开启注解式缓存
 32 //继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
 33 public class RedisConfig extends CachingConfigurerSupport {
 34 
 35     /**
 36      * 生成key的策略 根据类名+方法名+所有参数的值生成唯一的一个key
 37      *
 38      * @return
 39      */
 40     @Bean
 41     @Override
 42     public KeyGenerator keyGenerator() {
 43         return new KeyGenerator() {
 44             @Override
 45             public Object generate(Object target, Method method, Object... params) {
 46                 StringBuilder sb = new StringBuilder();
 47                 sb.append(target.getClass().getName());
 48                 sb.append(method.getName());
 49                 for (Object obj : params) {
 50                     sb.append(obj.toString());
 51                 }
 52                 return sb.toString();
 53             }
 54         };
 55     }
 56 
 57     /**
 58      * 管理缓存
 59      *
 60      * @param redisConnectionFactory
 61      * @return
 62      */
 63     @Bean
 64     public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
 65         //通过Spring提供的RedisCacheConfiguration类,构造一个自己的redis配置类,从该配置类中可以设置一些初始化的缓存命名空间
 66         // 及对应的默认过期时间等属性,再利用RedisCacheManager中的builder.build()的方式生成cacheManager:
 67         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
 68         config = config.entryTtl(Duration.ofMinutes(1))     // 设置缓存的默认过期时间,也是使用Duration设置
 69                 .disableCachingNullValues();     // 不缓存空值
 70 
 71         // 设置一个初始化的缓存空间set集合
 72         Set<String> cacheNames = new HashSet<>();
 73         cacheNames.add("my-redis-cache1");
 74         cacheNames.add("my-redis-cache2");
 75 
 76         // 对每个缓存空间应用不同的配置
 77         Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
 78         configMap.put("my-redis-cache1", config);
 79         configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(120)));
 80 
 81         RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)     // 使用自定义的缓存配置初始化一个cacheManager
 82                 .initialCacheNames(cacheNames)  // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
 83                 .withInitialCacheConfigurations(configMap)
 84                 .build();
 85         return cacheManager;
 86     }
 87 
 88     @Bean
 89     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
 90         RedisTemplate<Object, Object> template = new RedisTemplate<>();
 91         template.setConnectionFactory(connectionFactory);
 92 
 93         //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
 94         Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
 95 
 96         ObjectMapper mapper = new ObjectMapper();
 97         mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
 98         mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
 99         serializer.setObjectMapper(mapper);
100 
101         template.setValueSerializer(serializer);
102         //使用StringRedisSerializer来序列化和反序列化redis的key值
103         template.setKeySerializer(new StringRedisSerializer());
104         template.afterPropertiesSet();
105         return template;
106     }
107 
108     @Bean
109     public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
110         StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
111         stringRedisTemplate.setConnectionFactory(factory);
112         return stringRedisTemplate;
113     }
114 
115 }

 配置application.yml

 1 server:
 2   port: 80
 3   servlet:
 4     context-path: /
 5 
 6 
 7 spring:
 8   datasource:
 9     #1.JDBC
10     type: com.alibaba.druid.pool.DruidDataSource
11     driver-class-name: com.mysql.jdbc.Driver
12     url: jdbc:mysql://localhost:3306/xufanqi?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
13     username: root
14     password: 123
15     druid:
16       #2.u8FDEu63A5u6C60u914Du7F6E
17       #u521Du59CBu5316u8FDEu63A5u6C60u7684u8FDEu63A5u6570u91CF u5927u5C0FuFF0Cu6700u5C0FuFF0Cu6700u5927
18       initial-size: 5
19       min-idle: 5
20       max-active: 20
21       #u914Du7F6Eu83B7u53D6u8FDEu63A5u7B49u5F85u8D85u65F6u7684u65F6u95F4
22       max-wait: 60000
23       #u914Du7F6Eu95F4u9694u591Au4E45u624Du8FDBu884Cu4E00u6B21u68C0u6D4BuFF0Cu68C0u6D4Bu9700u8981u5173u95EDu7684u7A7Au95F2u8FDEu63A5uFF0Cu5355u4F4Du662Fu6BEBu79D2
24       time-between-eviction-runs-millis: 60000
25       # u914Du7F6Eu4E00u4E2Au8FDEu63A5u5728u6C60u4E2Du6700u5C0Fu751Fu5B58u7684u65F6u95F4uFF0Cu5355u4F4Du662Fu6BEBu79D2
26       min-evictable-idle-time-millis: 30000
27       validation-query: SELECT 1 FROM DUAL
28       test-while-idle: true
29       test-on-borrow: true
30       test-on-return: false
31       # u662Fu5426u7F13u5B58preparedStatementuFF0Cu4E5Fu5C31u662FPSCache  u5B98u65B9u5EFAu8BAEMySQLu4E0Bu5EFAu8BAEu5173u95ED   u4E2Au4EBAu5EFAu8BAEu5982u679Cu60F3u7528SQLu9632u706Bu5899 u5EFAu8BAEu6253u5F00
32       pool-prepared-statements: true
33       max-pool-prepared-statement-per-connection-size: 20
34       # u914Du7F6Eu76D1u63A7u7EDFu8BA1u62E6u622Au7684filtersuFF0Cu53BBu6389u540Eu76D1u63A7u754Cu9762sqlu65E0u6CD5u7EDFu8BA1uFF0C'wall'u7528u4E8Eu9632u706Bu5899
35       filter:
36         stat:
37           merge-sql: true
38           slow-sql-millis: 5000
39       #3.u57FAu7840u76D1u63A7u914Du7F6E
40       web-stat-filter:
41         enabled: true
42         url-pattern: /*
43         #u8BBEu7F6Eu4E0Du7EDFu8BA1u54EAu4E9BURL
44         exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
45         session-stat-enable: true
46         session-stat-max-count: 100
47       stat-view-servlet:
48         enabled: true
49         url-pattern: /druid/*
50         reset-enable: true
51         #u8BBEu7F6Eu76D1u63A7u9875u9762u7684u767Bu5F55u540Du548Cu5BC6u7801
52         login-username: admin
53         login-password: admin
54         allow: 127.0.0.1
55         #deny: 192.168.1.100
56   redis:
57     database: 0
58     host: 192.168.183.131
59     port: 6379
60     password: 123456
61     jedis:
62       pool:
63         max-active: 100
64         max-idle: 3
65         max-wait: -1
66         min-idle: 0
67     timeout: 1000
68 #pagehelperu5206u9875u63D2u4EF6u914Du7F6E
69 pagehelper:
70   helperDialect: mysql
71   reasonable: true
72   supportMethodsArguments: true
73   params: count=countSql
74 
75 #u663Eu793Au65E5u5FD7
76 logging:
77   level:
78     com.javaxl.springboot02.mapper: debug

整合ehcache的时候,会有一个配置文件spring-ehcache.xml

1 <!-- 使用ehcache缓存 -->
2     <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
3         <property name="configLocation" value="classpath:ehcache.xml"/>
4         <property name="shared" value="true"></property>
5     </bean>
6     <!-- 默认是cacheManager -->
7     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
8         <property name="cacheManager" ref="cacheManagerFactory"/>
9     </bean>

ehcache.xml

 1 <!--defaultCache:默认的管理策略-->
 2     <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
 3     <!--maxElementsInMemory:在内存中缓存的element的最大数目-->
 4     <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
 5     <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
 6     <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
 7     <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
 8     <!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
 9     <!--FIFO:first in first out (先进先出)-->
10     <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
11     <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
12     <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
13                   timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>

ssm框架中整合redis,那么会有个spring-redis.xml配置文件

 1 <!-- 1. 引入properties配置文件 -->
 2     <!--<context:property-placeholder location="classpath:redis.properties" />-->
 3 
 4     <!-- 2. redis连接池配置-->
 5     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
 6         <!--最大空闲数-->
 7         <property name="maxIdle" value="${redis.maxIdle}"/>
 8         <!--连接池的最大数据库连接数  -->
 9         <property name="maxTotal" value="${redis.maxTotal}"/>
10         <!--最大建立连接等待时间-->
11         <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
12         <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
13         <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
14         <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
15         <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
16         <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
17         <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
18         <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
19         <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
20         <!--在空闲时检查有效性, 默认false  -->
21         <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
22     </bean>
23 
24     <!-- 3. redis连接工厂 -->
25     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
26           destroy-method="destroy">
27         <property name="poolConfig" ref="poolConfig"/>
28         <!--IP地址 -->
29         <property name="hostName" value="${redis.hostName}"/>
30         <!--端口号  -->
31         <property name="port" value="${redis.port}"/>
32         <!--如果Redis设置有密码  -->
33         <property name="password" value="${redis.password}"/>
34         <!--客户端超时时间单位是毫秒  -->
35         <property name="timeout" value="${redis.timeout}"/>
36     </bean>
37 
38     <!-- 4. redis操作模板,使用该对象可以操作redis  -->
39     <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
40         <property name="connectionFactory" ref="connectionFactory"/>
41         <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
42         <property name="keySerializer">
43             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
44         </property>
45         <property name="valueSerializer">
46             <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
47         </property>
48         <property name="hashKeySerializer">
49             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
50         </property>
51         <property name="hashValueSerializer">
52             <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
53         </property>
54         <!--开启事务  -->
55         <property name="enableTransactionSupport" value="true"/>
56     </bean>
57 
58     <!-- 5.使用中间类解决RedisCache.RedisTemplate的静态注入,从而使MyBatis实现第三方缓存 -->
59     <bean id="redisCacheTransfer" class="com.javaxl.ssm2.util.RedisCacheTransfer">
60         <property name="redisTemplate" ref="redisTemplate"/>
61     </bean>

其中前面redis链接工厂的创建,已经交于springboot中的application.yml文件来完成。所以,springboot整合redis我们只需要关注下面这部分配置。

 1 @Bean
 2     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
 3         RedisTemplate<Object, Object> template = new RedisTemplate<>();
 4         template.setConnectionFactory(connectionFactory);
 5  
 6         //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
 7         Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
 8  
 9         ObjectMapper mapper = new ObjectMapper();
10         mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
11         mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
12         serializer.setObjectMapper(mapper);
13  
14         template.setValueSerializer(serializer);
15         //使用StringRedisSerializer来序列化和反序列化redis的key值
16         template.setKeySerializer(new StringRedisSerializer());
17         template.afterPropertiesSet();
18         return template;
19     }
20  
21     @Bean
22     public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
23         StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
24         stringRedisTemplate.setConnectionFactory(factory);
25         return stringRedisTemplate;
26     }
27  
28 }

SpringBoot整合redis及其注解式开发

@Cacheable:作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
主要参数说明:
1) value :
缓存的名称,在 spring 配置文件中定义,必须指定至少一个,
例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}。
2) key :缓存的 key,可以为空,
如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合,
例如:@Cacheable(value=”testcache”,key=”#userName”)。
3) condition :缓存的条件,可以为空,

Service 层

BookService 
 1 package com.javaqi.springboot002.Service;
 2 
 3 import com.javaqi.springboot002.entity.Book;
 4 import com.javaqi.springboot002.util.PageBean;
 5 import org.springframework.cache.annotation.CachePut;
 6 import org.springframework.cache.annotation.Cacheable;
 7 
 8 import java.util.List;
 9 
10 public interface BookService {
11 
12     int deleteByPrimaryKey(Integer bid);
13 
14     @Cacheable(value = "my-redis-cache1",condition ="#bid>20",key = "'bookid:'+#bid")
15     Book selectByPrimaryKey(Integer bid);
16     @CachePut(value = "my-redis-cache2")
17     List<Book> listPager(Book book, PageBean pageBean);
18 
19 }

测试:

 1 package com.javaqi.springboot002.Service.impl;
 2 
 3 
 4 import com.javaqi.springboot002.Service.BookService;
 5 import com.javaqi.springboot002.entity.Book;
 6 import com.javaqi.springboot002.util.PageBean;
 7 import org.junit.jupiter.api.Test;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.boot.test.context.SpringBootTest;
10 
11 /**
12  * @author XuFanQi
13  * @site
14  * @company
15  * @create 2019-11-28 16:46
16  */
17 @SpringBootTest
18 public class BookServiceImplTest {
19     @Autowired
20     private BookService bookService;
21 
22     @Test
23     public void deleteByPrimaryKey() {
24         bookService.deleteByPrimaryKey(21);
25 
26     }
27 
28     @Test
29     public void selectByPrimaryKey() {
30         System.out.println(bookService.selectByPrimaryKey(25));
31     }
32     @Test
33     public void listPager() {
34         Book book = new Book();
35         book.setBname("%圣墟%");
36         PageBean pageBean = new PageBean();
37         pageBean.setPage(2);
38         for (Book book1 : bookService.listPager(book, pageBean)) {
39             System.out.println(book1);
40         }
41     }
42 
43 }

 
原文地址:https://www.cnblogs.com/xcn123/p/11961843.html