spring同时整合redis和ehcache

本文介绍了如何在Spring应用中同时整合Redis和Ehcache,实现远程与本地缓存的结合。通过调整Maven依赖并配置注解,可以根据不同场景选择使用指定的缓存。两种指定缓存管理器的方法包括:在注解中直接指定或自定义实现Spring的缓存管理器接口。

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;

@Repository
public 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";

	@Override
	public Cache getCache(String name) {
		if (name.startsWith(redisPrefix))  {
			 return redisCacheManager.getCache(name);  
		} else {
			return ehCacheManager.getCache(name);  
		}
	}

	@Override
	public 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;

	@Override
	public 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")
	@Override
	public 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;
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值