redis+spring

1. 在配置文件中添加 注解 <cache:annotation-driven cache-manager="cacheManager" key-generator="keyGenerator" />

2.定义缓存管理侧率

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<ref bean="sharedCache1" />
<ref bean="sharedCache2" />
</set>
</property>
</bean>

3 实际的缓存处理类 

<bean id="sharedCache1" class="cache.redis.DataCache">
<constructor-arg name="name" value="default" />
<constructor-arg name="cacheService" ref="cacheService" />
</bean>
<bean id="sharedCache2" class="cache.redis.DataCache">
<constructor-arg name="name" value="cache2s" />
<constructor-arg name="cacheService" ref="cacheService" />
<property name="expire" value="2" />
</bean>

4. 配置jedisPoolConfig

JedisPoolConfig config = new JedisPoolConfig();

config.setMaxActive(Integer.parseInt(cachebundle.getString("redis.pool.maxActive")));
config.setMaxIdle(Integer.parseInt(cachebundle.getString("redis.pool.maxIdle")));
config.setMaxWait(Long.parseLong(cachebundle.getString("redis.pool.maxWait")));
config.setTestOnBorrow(Boolean.parseBoolean(cachebundle.getString("redis.pool.testOnBorrow")));
config.setTestOnReturn(Boolean.parseBoolean(cachebundle.getString("redis.pool.testOnReturn")));

5 生成一个jedisPool

JedisPool pool4master = new JedisPool(config, cachebundle.getString("cache.redis.host"), Integer.parseInt(cachebundle.getString("cache.redis.port")), Integer.parseInt(cachebundle.getString("redis.pool.timeout")));

6.得到一个jedis连接

jedis = pools.get(MASTER_KEY_PREFIX).getResource();

7.释放一个jedis连接

pools.get(MASTER_KEY_PREFIX).returnBrokenResource(jedis);

8.设置redis主库值

public static void set(Object key, Object value, int expire) {
Jedis redis = getRedisConnection();
byte[] skey = SerializationUtils.serialize(toSerializable(key));
byte[] svalue = SerializationUtils.serialize(toSerializable(value));
redis.set(skey, svalue);
redis.expire(skey, expire);
returnResource(redis);
}

9.从redis丛库得到一个值

public static Object get(Object key) {
Jedis redis = getSlaveRedisConnection();
byte[] result = redis.get(SerializationUtils.serialize(toSerializable(key)));
returnSlaveResource(redis);
return result == null ? null : SerializationUtils.deserialize(result);
}

 总结:

  1、用了spring的cache标签 ,cache:annotation-driven,定义了cache管理器  cache-manager,及key的生成策略

  2.cachemanage的策略为org.springframework.cache.support.SimpleCacheManager,具体的实现类为DataCache

  3.DataCache 这个引用了CacheService的服务

  4.CacheService调用了CacheRedisAccessor,针对redis客户端的一个包装,初始化JedisPoolConfig及 JedisPool,实现了主从结构,初始化两个jedispool,从pool中取jedis连接。其中的key和value都为byte[]类型,用序列化和反序列化。

redis分布式缓存集群配置参考:

https://www.jerrylou.me/redis/redis-cache-intro-20170125.html

http://www.thinksaas.cn/topics/0/515/515811.html

http://dbaplus.cn/news-21-239-1.html

 http://dbaplus.cn/news-21-774-1.html

https://juejin.im/entry/56baa0cfc4c97100522945d3

原文地址:https://www.cnblogs.com/suixin84/p/6700441.html