redis与spring的完全集成

下载spring-data-redis,gav如下:

  1. <dependency>
  2. <groupId>org.springframework.data</groupId>
  3. <artifactId>spring-data-redis</artifactId>
  4. <version>1.0.1.RELEASE</version>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>org.slf4j</groupId>
  8. <artifactId>slf4j-log4j12</artifactId>
  9. </exclusion>
  10. <exclusion>
  11. <groupId>org.slf4j</groupId>
  12. <artifactId>jcl-over-slf4j</artifactId>
  13. </exclusion>
  14. </exclusions>
  15. </dependency>
                  <dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.0.1.RELEASE</version>
			<exclusions>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-log4j12</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>jcl-over-slf4j</artifactId>
				</exclusion>
			</exclusions>

		</dependency>


其中exclusion了两个包,原因是与项目里其它包冲突。

bean配置如下,可在web.xml里配置加载bean文件:

  1. <bean id="redisCacheManager" class="com.cr.common.cache.base.RedisCacheManger">
  2. <property name="pool" ref="shardedJedisPool"/>
  3. </bean>
  4. <!-- jedis 连接池配置-->
  5. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  6. <property name="maxActive" value="${redis.pool.maxActive}" />
  7. <property name="maxIdle" value="${redis.pool.maxIdle}" />
  8. <property name="maxWait" value="${redis.pool.maxWait}" />
  9. <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
  10. </bean>
  11. <!-- jedis 多个服务器配置-->
  12. <bean id="jedisShardInfo1" class="redis.clients.jedis.JedisShardInfo">
  13. <constructor-arg index="0" value="${redis2.ip}" />
  14. <constructor-arg index="1" value="${redis.port}" type="int" />
  15. </bean>
  16. <bean id="jedisShardInfo2" class="redis.clients.jedis.JedisShardInfo">
  17. <constructor-arg index="0" value="${redis.ip}" />
  18. <constructor-arg index="1" value="${redis.port}" type="int" />
  19. </bean>
  20. <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
  21. <constructor-arg index="0" ref="jedisPoolConfig" />
  22. <constructor-arg index="1">
  23. <list>
  24. <ref bean="jedisShardInfo1" />
  25. <ref bean="jedisShardInfo2"/>
  26. </list>
  27. </constructor-arg>
  28. </bean>
  29. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
  30. >
  31. <property name="hostName" value="${redis.ip}" />
  32. <property name="port" value="${redis.port}" />
  33. <property name="poolConfig" ref="jedisPoolConfig" />
  34. <!--<property name="shardInfo" ref="shardedJedisPool"></property>-->
  35. </bean>
  36. <context:property-placeholder location="/WEB-INF/spring/SystemContext.properties"/>
  37. <context:component-scan base-package="org.springframework.data.redis.samples"/>
	<bean id="redisCacheManager" class="com.cr.common.cache.base.RedisCacheManger">
		<property name="pool" ref="shardedJedisPool"/>
	</bean>
	<!-- jedis 连接池配置-->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
		<property name="maxActive"     value="${redis.pool.maxActive}" />  
		<property name="maxIdle"       value="${redis.pool.maxIdle}" />  
		<property name="maxWait"       value="${redis.pool.maxWait}" />  
		<property name="testOnBorrow"  value="${redis.pool.testOnBorrow}" />  
	</bean>  
	<!-- jedis 多个服务器配置-->
	<bean id="jedisShardInfo1" class="redis.clients.jedis.JedisShardInfo">  
		<constructor-arg index="0" value="${redis2.ip}" />  
		<constructor-arg index="1" value="${redis.port}" type="int" />  
	</bean>	
	
	<bean id="jedisShardInfo2" class="redis.clients.jedis.JedisShardInfo">  
		<constructor-arg index="0" value="${redis.ip}" />  
		<constructor-arg index="1" value="${redis.port}" type="int" />  
	</bean>	
	
	<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">  
		<constructor-arg index="0" ref="jedisPoolConfig" />  
		<constructor-arg index="1">
			<list>
				<ref bean="jedisShardInfo1" />
				<ref bean="jedisShardInfo2"/>
			</list>
		</constructor-arg>  
	</bean>
	
	<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		>
		<property name="hostName"   value="${redis.ip}" />  
		<property name="port"       value="${redis.port}" />  
		<property name="poolConfig" ref="jedisPoolConfig" /> 
	
		<!--<property name="shardInfo"  ref="shardedJedisPool"></property>-->
	</bean> 
     
	<context:property-placeholder  location="/WEB-INF/spring/SystemContext.properties"/> 
	<context:component-scan base-package="org.springframework.data.redis.samples"/>
        

属性文件内容如下:

  1. redis.ip=192.168.1.110
  2. redis2.ip=192.168.1.112
  3. #Port
  4. redis.port=6379
  5. #最大分配的对象数
  6. redis.pool.maxActive=1024
  7. #最大能够保持idel状态的对象数
  8. redis.pool.maxIdle=200
  9. #当池内没有返回对象时,最大等待时间
  10. redis.pool.maxWait=1000
  11. #当调用borrow Object方法时,是否进行有效性检查
  12. redis.pool.testOnBorrow=true
  13. #当调用return Object方法时,是否进行有效性检查
  14. redis.pool.testOnReturn=true
redis.ip=192.168.1.110
redis2.ip=192.168.1.112
#Port   
redis.port=6379

#最大分配的对象数 
redis.pool.maxActive=1024
#最大能够保持idel状态的对象数
redis.pool.maxIdle=200
#当池内没有返回对象时,最大等待时间
redis.pool.maxWait=1000
#当调用borrow Object方法时,是否进行有效性检查 
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查   
redis.pool.testOnReturn=true


缓存管理接口:

  1. public interface RedisCache {
  2. public <T> T getRedisCacheInfo(String key);
  3. public <T> boolean setRedisCacheInfo(String key, T value);
  4. }
public interface RedisCache {
	
	public <T> T getRedisCacheInfo(String key);

	public <T> boolean setRedisCacheInfo(String key, T value);
	
}


缓存管理实现:

  1. public class RedisCacheManger implements RedisCache {
  2. private ShardedJedisPool pool ;
  3. private Logger log = Logger.getLogger(RedisCacheManger.class);
  4. public ShardedJedisPool getPool() {
  5. return pool;
  6. }
  7. public void setPool(ShardedJedisPool pool) {
  8. this.pool = pool;
  9. }
  10. public <T> T getRedisCacheInfo(String key) {
  11. try {
  12. log.info("get from redisCache :"+key);
  13. System.out.println("get from rediscache");
  14. ShardedJedis jedis = pool.getResource();
  15. pool.returnResource(jedis);
  16. return (T)jedis.get(key);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. return null;
  21. }
  22. public <T> boolean setRedisCacheInfo(String key, T value) {
  23. try {
  24. log.info("add to redisCache :"+key);
  25. System.out.println("add to rediscache");
  26. ShardedJedis jedis = pool.getResource();
  27. jedis.set(key, (String)value);
  28. pool.returnResource(jedis);
  29. return true;
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. return false;
  34. }
  35. public static void main(String[] args) {
  36. new RedisCacheManger().setRedisCacheInfo("12345", "asdfg");
  37. }
  38. }
public class RedisCacheManger implements RedisCache {
	
	private ShardedJedisPool pool ;
	
	private Logger log = Logger.getLogger(RedisCacheManger.class); 
	public ShardedJedisPool getPool() {
		return pool;
	}

	public void setPool(ShardedJedisPool pool) {
		this.pool = pool;
	}

	public <T> T getRedisCacheInfo(String key) {
		
		try {
			log.info("get from redisCache :"+key);
			System.out.println("get from rediscache");
			ShardedJedis jedis = pool.getResource();
			pool.returnResource(jedis);
			return (T)jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
 

	public <T> boolean setRedisCacheInfo(String key, T value) {

		try {
			log.info("add to redisCache :"+key);
			System.out.println("add to rediscache");
			ShardedJedis jedis = pool.getResource();
			jedis.set(key, (String)value);
			pool.returnResource(jedis);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	public static void main(String[] args) {
		new RedisCacheManger().setRedisCacheInfo("12345", "asdfg");
	}
}


缓存切面注解:

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface NeedRedisCached {}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NeedRedisCached {}


缓存切面处理类:

  1. @Aspect
  2. public class RedisCacheAspect implements Ordered {
  3. private static Logger log = Logger.getLogger(RedisCacheAspect.class);
  4. private RedisCache redisCacheManager;
  5. private int orderValue = 3;
  6. public RedisCache getRedisCacheManager() {
  7. return redisCacheManager;
  8. }
  9. public void setRedisCacheManager(RedisCache redisCacheManager) {
  10. this.redisCacheManager = redisCacheManager;
  11. }
  12. @Pointcut("@annotation(com.jd.bi.odp.common.cache.core.NeedRedisCached)")
  13. public void needRedisCached() {
  14. }
  15. @Around("needRedisCached() && args(filter,..)")
  16. public Object aroundInvoke(ProceedingJoinPoint pjp, QueryFilter filter) throws Throwable {
  17. log.info("enter aroundInvoke!!!");
  18. if (filter.getValue() == null) {
  19. return null;
  20. }
  21. boolean cacheEnabled = CommonUtil.parseBoolean(HBaseConfig.getProperty("redisCache.enabled"), false);
  22. if (cacheEnabled) {
  23. String md5key = MD5Util.getMD5(filter.getValue().toString());
  24. Object value = redisCacheManager.getRedisCacheInfo(md5key);
  25. boolean flag = false;
  26. if (null != value) {
  27. JSONObject json = new JSONObject(value.toString());
  28. return json;
  29. } else if ("null".equals(value)) {
  30. return null;
  31. } else { //执行hbase查询
  32. value = pjp.proceed();
  33. if(null!=value){//此处根据业务逻辑判断不缓存的条件
  34. }
  35. else{
  36. flag = redisCacheManager.setRedisCacheInfo(md5key, value.toString());
  37. if(flag)
  38. log.info("add a cache success by key: "+md5key);
  39. else
  40. log.warn("add a cache failure by key: "+md5key);
  41. }
  42. }
  43. return value;
  44. }
  45. } else {// 执行hbase查询
  46. return pjp.proceed();
  47. }
  48. }
  49. @Override
  50. public int getOrder() {
  51. return orderValue;
  52. }
  53. public int getOrderValue() {
  54. return orderValue;
  55. }
  56. public void setOrderValue(int orderValue) {
  57. this.orderValue = orderValue;
  58. }
  59. }
@Aspect
public class RedisCacheAspect implements Ordered {
	
	private static Logger log = Logger.getLogger(RedisCacheAspect.class); 
	private RedisCache redisCacheManager;
	private int orderValue = 3;
	public RedisCache getRedisCacheManager() {
		return redisCacheManager;
	}

	public void setRedisCacheManager(RedisCache redisCacheManager) {
		this.redisCacheManager = redisCacheManager;
	}

	@Pointcut("@annotation(com.jd.bi.odp.common.cache.core.NeedRedisCached)")
	public void needRedisCached() {

	}
	
	@Around("needRedisCached() && args(filter,..)")
	public Object aroundInvoke(ProceedingJoinPoint pjp, QueryFilter filter) throws Throwable {
		log.info("enter aroundInvoke!!!");
		if (filter.getValue() == null) {
			return null;
		}

		boolean cacheEnabled = CommonUtil.parseBoolean(HBaseConfig.getProperty("redisCache.enabled"), false);

		if (cacheEnabled) {
			
			String md5key = MD5Util.getMD5(filter.getValue().toString());
			Object value = redisCacheManager.getRedisCacheInfo(md5key);
			boolean flag = false;
			if (null != value) {

				JSONObject json = new JSONObject(value.toString());
				return json;
			} else if ("null".equals(value)) {
				return null;
			} else { //执行hbase查询
				value = pjp.proceed();
				if(null!=value){//此处根据业务逻辑判断不缓存的条件
					}
					else{
						flag = redisCacheManager.setRedisCacheInfo(md5key, value.toString());
						
						if(flag)
							log.info("add a cache success by key: "+md5key);
						else
							log.warn("add a cache failure by key: "+md5key);
					}
				}
				return value;
			}
		} else {// 执行hbase查询
			return pjp.proceed();
		}
	}
	@Override
	public int getOrder() {
		return orderValue;
	}
	public int getOrderValue() {
		return orderValue;
	}

	public void setOrderValue(int orderValue) {
		this.orderValue = orderValue;
	}
}


缓存存在直接返回,不存在的话执行数据源查询,此处是hbase查询,并设置缓存。

切面配置:

  1. <!-- redis缓存运行切面 -->
  2. <bean id="RedisCacheAspect"
  3. class="com.cr.common.cache.core.RedisCacheAspect">
  4. <property name="orderValue" value="3" />
  5. <property name="redisCacheManager" ref="redisCacheManager"/>
  6. </bean>
  7. <!-- 切面申明配置-->
  8. <aop:aspectj-autoproxy>
  9. <aop:include name="RedisCacheAspect" />
  10. </aop:aspectj-autoproxy>
	<!-- redis缓存运行切面 -->
	<bean id="RedisCacheAspect"
		class="com.cr.common.cache.core.RedisCacheAspect">
		<property name="orderValue" value="3" />
		<property name="redisCacheManager" ref="redisCacheManager"/>
	</bean>
	<!-- 切面申明配置-->
	<aop:aspectj-autoproxy>
		<aop:include name="RedisCacheAspect" />
	</aop:aspectj-autoproxy>
	


此时,前端web页面用户的访问触发的action如果满足条件,则会进入切面方法处理,完成redis缓存的使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值