mybatis 整合redis作为二级缓存

核心关键在于定义一个RedisCache实现mytis实现的Cache接口

 1 **
 2  * @author tele
 3  * @Description RedisCache由于需要传入id, 由mybatis进行创建,所以如果需要为RedisCache注入RedisTemplateUtil,直接使用@Autowired无效
 4  * @create 2019-09-07
 5  */
 6 public class RedisCache implements Cache {
 7 
 8     private static RedisTemplateUtil templateUtil;
 9 
10     public static void setTemplateUtil(RedisTemplateUtil templateUtil) {
11         RedisCache.templateUtil = templateUtil;
12     }
13 
14     //这个id实际是传入的mapper全限定名
15     private final String id;
16 
17     public RedisCache(final String id) {
18         if (id == null) {
19             throw new IllegalArgumentException("Cache instances require an ID");
20         }
21         this.id = id;
22     }
23 
24     public String getId() {
25         return id;
26     }
27 
28     public void putObject(Object key, Object value) {
29         templateUtil.set(key, value);
30     }
31 
32     public Object getObject(Object key) {
33         return templateUtil.get(key);
34     }
35 
36     public Object removeObject(Object key) {
37         return null;
38     }
39 
40     public void clear() {
41         templateUtil.clear();
42     }
43 
44     public int getSize() {
45         return templateUtil.getSize();
46     }
47 
48     public ReadWriteLock getReadWriteLock() {
49         return null;
50     }
51 }

定义中间类,注入工具类

 1 @Component
 2 public class RedisCacheTransfer {
 3     @Autowired
 4     private RedisTemplateUtil redisTemplateUtil;
 5 
 6     @Autowired
 7     public void setRedisTemplateUtil(){
 8         RedisCache.setTemplateUtil(redisTemplateUtil);
 9     }
10 }

工具类

 1 /**
 2  * @author tele
 3  * @Description
 4  * @create 2019-09-09
 5  */
 6 @Component
 7 public class RedisTemplateUtil {
 8     @Autowired
 9     private RedisTemplate template;
10 
11 
12     public Object get(Object key) {
13         return template.opsForValue().get(key);
14     }
15 
16     public void set(Object key,Object value){
17         template.opsForValue().set(key, value);
18     }
19 
20     public int getSize() {
21       int size = (int) template.execute((RedisCallback<Integer>) connection -> {
22             return connection.dbSize().intValue();
23       });
24       return size;
25     }
26 
27     public void clear() {
28         template.execute((RedisCallback)  connection -> {
29             connection.flushDb();
30             return null;
31         });
32     }
33 }

在对应的mapper.xml中添加cache标签

测试的时候还是先加载ClassPathXmlContext,然后获得sqlSession,注意mybatis的增删改,flushCache=true,可如果你没有调用commit并不会清空缓存

applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:p="http://www.springframework.org/schema/p"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
 8 
 9     <context:component-scan base-package="cn.tele"/>
10 
11     <context:property-placeholder location="classpath:redis.properties,db.properties"/>
12 
13 
14     <!--数据源-->
15     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
16         <property name="jdbcUrl" value="${db.url}"/>
17         <property name="driverClass" value="${db.driver}"/>
18         <property name="user" value="${db.username}"/>
19         <property name="password" value="${db.password}"/>
20         <property name="initialPoolSize" value="${db.initialPoolSize}"/>
21         <property name="maxPoolSize" value="${db.maxPoolSize}"/>
22         <property name="maxIdleTime" value="${db.maxIdleTime}"/>
23         <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}"/>
24         <property name="testConnectionOnCheckout" value="true"/>
25       </bean>
26 
27 
28     <!--mybatis-->
29     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
30         <property name="mapperLocations" value="classpath*:cn/tele/bean/**/*.xml"/>
31         <property name="dataSource" ref="dataSource"/>
32         <property name="configurationProperties">
33             <props>
34                 <prop key="cacheEnabled">true</prop>
35                 <prop key="jdbcTypeForNull">NULL</prop>
36                 <prop key="lazyLoadingEnabled">true</prop>
37                 <prop key="aggressiveLazyLoading">false</prop>
38             </props>
39         </property>
40     </bean>
41 
42     <!--扫描mapper-->
43     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
44         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
45         <property name="basePackage" value="cn.tele"/>
46     </bean>
47 
48 
49     <!--redis连接池属性设置-->
50     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
51         <property name="maxIdle" value="${redis.maxIdle}"/>
52         <property name="maxTotal" value="${redis.maxTotal}"/>
53     </bean>
54 
55     <bean id="jedisConnFactory"
56           class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
57           p:poolConfig-ref="poolConfig"  p:port="${redis.port}" p:hostName="${redis.host}"/>
58 
59     <bean id="redisTemplate"
60           class="org.springframework.data.redis.core.StringRedisTemplate"
61           p:connection-factory-ref="jedisConnFactory">
62         <!--序列化策略-->
63         <property name="keySerializer">
64             <bean class="org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer">
65                 <constructor-arg type="java.lang.Class" value="java.lang.String"/>
66             </bean>
67         </property>
68 
69         <property name="valueSerializer">
70             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer">
71 
72             </bean>
73         </property>
74 
75         <property name="hashKeySerializer">
76             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
77         </property>
78 
79         <property name="hashValueSerializer">
80             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
81         </property>
82     </bean>
83 </beans>

猜你喜欢

转载自www.cnblogs.com/tele-share/p/11529575.html