spring同时整合redis和ehcache

来源:互联网 发布:京宽网络24客服电话 编辑:程序博客网 时间:2024/06/05 00:27

spring同时整合redis和ehcache3,远程缓存和本地缓存同时使用,配置注解根据不同的使用场景和数据选择指定缓存。

1.maven依赖。注意版本兼容,开始就被版本问题坑了下。

<dependency>        <groupId>org.springframework.data</groupId>       <artifactId>spring-data-redis</artifactId>        <version>1.8.0.RELEASE</version>    </dependency>        <dependency>        <groupId>redis.clients</groupId>       <artifactId>jedis</artifactId>        <version>2.9.0</version>    </dependency>        <dependency>        <groupId>org.apache.commons</groupId>       <artifactId>commons-pool2</artifactId>        <version>2.4.2</version>    </dependency>        <dependency>    <groupId>org.ehcache</groupId>    <artifactId>ehcache</artifactId>    <version>3.4.0</version></dependency>  <dependency>    <groupId>javax.cache</groupId>    <artifactId>cache-api</artifactId>  <version>1.0.0</version>  </dependency> 

2.配置文件
<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"        xmlns:aop="http://www.springframework.org/schema/aop"         xmlns:tx="http://www.springframework.org/schema/tx"        xmlns:cache="http://www.springframework.org/schema/cache"        xsi:schemaLocation="http://www.springframework.org/schema/context                             http://www.springframework.org/schema/context/spring-context.xsd         http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd       http://www.springframework.org/schema/aop       http://www.springframework.org/schema/apo/spring-aop.xsd         http://www.springframework.org/schema/tx                     http://www.springframework.org/schema/tx/spring-tx.xsd                   http://www.springframework.org/schema/cache                   http://www.springframework.org/schema/cache/spring-cache.xsd">      <!-- remote redis -->    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">    <property name="maxTotal" value="50"></property>    <property name="maxIdle" value="20"></property>    <property name="minIdle" value="10"></property>    <property name="maxWaitMillis" value="3000"></property>    <property name="testWhileIdle" value="false"/>    </bean>                     <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><property name="hostName" value="10.20.130.34"></property><property name="port" value="4544"></property><property name="password" value="paic1234"></property><property name="poolConfig" ref="jedisPoolConfig"></property></bean><bean id="springDataRedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"><property name="connectionFactory" ref="jedisConnectionFactory"></property><!-- 序列化 --><property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean></property><property name="hashKeySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean></property><property name="valueSerializer"><bean class="com.caiwufei.entity.base.BaseEntity"></bean></property><property name="hashValueSerializer"><bean class="com.caiwufei.entity.base.BaseEntity"></bean></property></bean><bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"><constructor-arg type="org.springframework.data.redis.core.RedisOperations" ref="springDataRedisTemplate" /></bean><!-- local ehcache --><bean id="jCacheManagerFactoryBean" class="org.springframework.cache.jcache.JCacheManagerFactoryBean">      <property name="cacheManagerUri" value="classpath:/config/ehcache.xml" />  </bean>  <bean id="jCacheCacheManager" class="org.springframework.cache.jcache.JCacheCacheManager">      <property name="cacheManager" ref="jCacheManagerFactoryBean" />  </bean>  <!-- mix cacheManager --><!-- <bean id="cacheManager" class="com.caiwufei.common.cache.AppCacheManager"><property name="redisCacheManager" ref="redisCacheManager"/><property name="ehCacheManager" ref="jCacheCacheManager"/></bean><cache:annotation-driven cache-manager="cacheManager"/>    --><cache:annotation-driven cache-manager="redisCacheManager"/>    <cache:annotation-driven cache-manager="jCacheCacheManager"/>    </beans>

3 代码

package com.caiwufei.dao.o2o;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Repository;import com.caiwufei.entity.base.BaseDao;import com.caiwufei.entity.o2o.AccountInfo;@Repositorypublic interface AccountInfoDao extends BaseDao<AccountInfo>{@Cacheable(cacheManager="jCacheCacheManager", cacheNames="SSAccountInfo", key="'accountId_' + #root.args[0].accountId")public AccountInfo queryByAccountIdForTestEhcache(AccountInfo a);@Cacheable(cacheManager="redisCacheManager", cacheNames="SSAccountInfo", key="'accountId_' + #root.args[0].accountId")public AccountInfo queryByAccountIdForTestRedis(AccountInfo a);}

4.想让数据缓存到指定的缓存中,有两个方式,两种方式亲测都是可以的:

1在注解中指定缓存管理器,cacheManager="jCacheCacheManager"或者cacheManager="redisCacheManager",此时配置xml的时候需要配置多条<cache:annotation-driven/> 并且指定缓存管理器,如同上面xml的配置;

2实现spring的缓存管理器接口,xml中的 AppCacheManager就是自己实现的类。此时只需要配置一条缓存注解驱动(AppCacheManager类下面有),这种方式需要在cacheNames中做出标志,使缓存管理器能够判断出该使用哪个缓存管理器。


xml上面有两个类是自己定义的。这里也顺便贴一下。

package com.caiwufei.common.cache;import java.util.ArrayList;import java.util.Collection;import org.springframework.cache.Cache;import org.springframework.cache.CacheManager;public class AppCacheManager implements CacheManager{private CacheManager redisCacheManager;  private CacheManager ehCacheManager; private final static String redisPrefix = "redis";@Overridepublic Cache getCache(String name) {if (name.startsWith(redisPrefix))  { return redisCacheManager.getCache(name);  } else {return ehCacheManager.getCache(name);  }}@Overridepublic Collection<String> getCacheNames() {    Collection<String> cacheNames = new ArrayList<String>();                  if (redisCacheManager != null) {              cacheNames.addAll(redisCacheManager.getCacheNames());          }          if (ehCacheManager != null) {              cacheNames.addAll(ehCacheManager.getCacheNames());          }                 return cacheNames;  }public CacheManager getRedisCacheManager() {return redisCacheManager;}public void setRedisCacheManager(CacheManager redisCacheManager) {this.redisCacheManager = redisCacheManager;}public CacheManager getEhCacheManager() {return ehCacheManager;}public void setEhCacheManager(CacheManager ehCacheManager) {this.ehCacheManager = ehCacheManager;}}

package com.caiwufei.entity.base;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.SerializationException;public class BaseEntity<T> implements Serializable, RedisSerializer<T>{/** *  */private static final long serialVersionUID = 3812075902697557491L;@Overridepublic byte[] serialize(T t) throws SerializationException {if (t == null) {            return new byte[0];        }ObjectOutputStream oos = null;        ByteArrayOutputStream baos = null;        try {            // 序列化            baos = new ByteArrayOutputStream();            oos = new ObjectOutputStream(baos);            oos.writeObject(t);            byte[] bytes = baos.toByteArray();            return bytes;        } catch (Exception e) {            e.printStackTrace();        }        return null;}@SuppressWarnings("unchecked")@Overridepublic T deserialize(byte[] bytes) throws SerializationException {if (bytes == null || bytes.length == 0) {        return null;    }ByteArrayInputStream bais = null;    try {         // 反序列化         bais = new ByteArrayInputStream(bytes);         ObjectInputStream ois = new ObjectInputStream(bais);         return (T) ois.readObject();    } catch (Exception e) {         e.printStackTrace();    }    return null;}}


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 凸镜原理 凹凹 凹甲 激凹 凹凹在线 凹凹啦 小学女生凹处高清图片 初中学生凹阴现沟 小学女生显凹沟图片 凹笔顺 凹的笔顺 三凹征 凹轮中国厕所 学生凹阴现沟 凹洞修复 车凹一块吸出来多少钱 女生凹沟图片能看里面 凹读音 凹的读音 脚底中间凹处痛 惠若琪凹点 凹透镜成像 凹凹夫妻在线 凹怎么读 七年级女生凹处照片 甲身凹沟 女少内裤凹进去 凹造型 凹透镜 凹透镜成像规律 凹凹啦批号在线查询 凹叶景天 痘疤修复凹洞痘坑1万够不够 凹凸图片 凹凸英雄 凹凸曼 凹凸学园 凹凸分类 凹凸笔顺 凹凸学院