您的位置:首页 > 数据库 > Redis

spring data RedisCacheManager 源码查看与配置解析

2017-07-13 18:16 507 查看
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns="http://www.springframework.org/schema/beans"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd" default-lazy-init="true">
<cache:annotation-driven cache-manager="cacheManagerNew"/>

<!-- jedis 连接池 配置 -->
<bean id="poolConfigNew" class="redis.clients.jedis.JedisPoolConfig" >
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>

<!-- 集群
<bean id="redisClusterConfigurationNew" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
<property name="maxRedirects" value="${redis.maxRedirects}"></property>
<property name="clusterNodes">
<set>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg name="host" value="${redis.host1}"/>
<constructor-arg name="port" value="${redis.port1}"/>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg name="host" value="${redis.host2}"/>
<constructor-arg name="port" value="${redis.port2}"/>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg name="host" value="${redis.host3}"/>
<constructor-arg name="port" value="${redis.port3}"/>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg name="host" value="${redis.host4}"/>
<constructor-arg name="port" value="${redis.port4}"/>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg name="host" value="${redis.host5}"/>
<constructor-arg name="port" value="${redis.port5}"/>
</bean>
<bean class="org.springframework.data.redis.connection.RedisClusterNode">
<constructor-arg name="host" value="${redis.host6}"/>
<constructor-arg name="port" value="${redis.port6}"/>
</bean>
</set>
</property>
</bean>

<bean id="connectionFactoryNew" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg name="poolConfig" ref="poolConfigNew"/>
<constructor-arg name="clusterConfig" ref="redisClusterConfigurationNew"/>
</bean>
-->

<!-- 单机 -->
<bean id="connectionFactoryNew"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.onehost}" p:port="${redis.oneport}" p:password="${redis.password}">
<constructor-arg name="poolConfig" ref="poolConfigNew"/>
</bean>

<bean id="stringRedisSerializerNew" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="jdkRedisSerializerNew" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
<bean id="commonRedisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="connectionFactoryNew" />
<property name="keySerializer" ref="stringRedisSerializerNew" />
<property name="hashKeySerializer" ref="stringRedisSerializerNew" />
<property name="valueSerializer" ref="jdkRedisSerializerNew" />
<property name="hashValueSerializer" ref="jdkRedisSerializerNew" />
</bean>

<!-- 配置缓存 5小时过期-->
<bean id="cacheManagerNew" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg ref="commonRedisTemplate" />
<constructor-arg name="cacheNames">
<set>
<value>defaultCache</value>
<value>recipeCache</value>
<value>adCache</value>
<value>recommendCache</value>
<value>pgcRecommendCache</value>
<value>videoCache</value>
<value>keywordsCache</value>
<value>ingredientCache</value>
<value>courseCache</value>
<value>topicCache</value>
</set>
</constructor-arg>
<property name="expires">
<map>
<entry key="topicCache" value="35000"/>
<entry key="recipeCache" value="35000"/>
<entry key="adCache" value="35000"/>
<entry key="recommendCache" value="35000"/>
</map>
</property>
</bean>

<bean id="redisUtils" class="com.common.RedisUtils">
<property name="commonRedisTemplate" ref="commonRedisTemplate"></property>
</bean>
</beans>


分割线------------------源码查看

/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao (cnfree2000@hotmail.com) ***/
package org.springframework.data.redis.cache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;
import org.springframework.cache.transaction.TransactionAwareCacheDecorator;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

public class RedisCacheManager extends AbstractTransactionSupportingCacheManager {
private final Log logger;
private final RedisOperations redisOperations;
private boolean usePrefix;
private RedisCachePrefix cachePrefix;
private boolean loadRemoteCachesOnStartup;
private boolean dynamic;
private long defaultExpiration;
private Map<String, Long> expires;
private Set<String> configuredCacheNames;

public RedisCacheManager(RedisOperations redisOperations) {
this(redisOperations, Collections.emptyList());
}

public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames) {
this.logger = LogFactory.getLog(RedisCacheManager.class);

this.usePrefix = false;
this.cachePrefix = new DefaultRedisCachePrefix();
this.loadRemoteCachesOnStartup = false;
this.dynamic = true;

this.defaultExpiration = 0L;
this.expires = null;

this.redisOperations = redisOperations;
setCacheNames(cacheNames);
}

public Cache getCache(String name) {
Cache cache = super.getCache(name);
if ((cache == null) && (this.dynamic)) {
return createAndAddCache(name);
}

return cache;
}

public void setCacheNames(Collection<String> cacheNames) {
Set newCacheNames = new HashSet(cacheNames);

this.configuredCacheNames = newCacheNames;
this.dynamic = newCacheNames.isEmpty();
}

public void setUsePrefix(boolean usePrefix) {
this.usePrefix = usePrefix;
}

public void setCachePrefix(RedisCachePrefix cachePrefix) {
this.cachePrefix = cachePrefix;
}

public void setDefaultExpiration(long defaultExpireTime) {
this.defaultExpiration = defaultExpireTime;
}

public void setExpires(Map<String, Long> expires) {
this.expires = ((expires != null) ? new ConcurrentHashMap(expires) : null);
}

public void setLoadRemoteCachesOnStartup(boolean loadRemoteCachesOnStartup) {
this.loadRemoteCachesOnStartup = loadRemoteCachesOnStartup;
}

protected Collection<? extends Cache> loadCaches() {
Assert.notNull(this.redisOperations, "A redis template is required in order to interact with data store");
return addConfiguredCachesIfNecessary(
(this.loadRemoteCachesOnStartup) ? loadAndInitRemoteCaches() : Collections.emptyList());
}

protected Collection<? extends Cache> addConfiguredCachesIfNecessary(Collection<? extends Cache> caches) {
Assert.notNull(caches, "Caches must not be null!");

Collection result = new ArrayList(caches);

for (String cacheName : getCacheNames()) {
boolean configuredCacheAlreadyPresent = false;

for (Cache cache : caches) {
if (cache.getName().equals(cacheName)) {
configuredCacheAlreadyPresent = true;
break;
}
}

if (!(configuredCacheAlreadyPresent)) {
result.add(getCache(cacheName));
}
}

return result;
}

protected Cache createAndAddCache(String cacheName) {
addCache(createCache(cacheName));
return super.getCache(cacheName);
}

protected RedisCache createCache(String cacheName) {
long expiration = computeExpiration(cacheName);
return new RedisCache(cacheName, (this.usePrefix) ? this.cachePrefix.prefix(cacheName) : null,
this.redisOperations, expiration);
}

protected long computeExpiration(String name) {
Long expiration = null;
if (this.expires != null) {
expiration = (Long) this.expires.get(name);
}
return ((expiration != null) ? expiration.longValue() : this.defaultExpiration);
}

protected List<Cache> loadAndInitRemoteCaches() {
List caches = new ArrayList();
try {
Set cacheNames = loadRemoteCacheKeys();
if (!(CollectionUtils.isEmpty(cacheNames))) {
for (String cacheName : cacheNames)
if (null == super.getCache(cacheName))
caches.add(createCache(cacheName));
}
} catch (Exception e) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Failed to initialize cache with remote cache keys.", e);
}
}

return caches;
}

protected Set<String> loadRemoteCacheKeys() {
return ((Set) this.redisOperations.execute(new RedisCallback() {
public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
Set keys = connection
.keys(RedisCacheManager.this.redisOperations.getKeySerializer().serialize("*~keys"));
Set cacheKeys = new LinkedHashSet();

if (!(CollectionUtils.isEmpty(keys))) {
for (byte[] key : keys) {
cacheKeys.add(RedisCacheManager.this.redisOperations.getKeySerializer().deserialize(key)
.toString().replace("~keys", ""));
}
}

return cacheKeys;
}
}));
}

protected RedisOperations getRedisOperations() {
return this.redisOperations;
}

protected RedisCachePrefix getCachePrefix() {
return this.cachePrefix;
}

protected boolean isUsePrefix() {
return this.usePrefix;
}

public void afterPropertiesSet() {
if (!(CollectionUtils.isEmpty(this.configuredCacheNames))) {
for (String cacheName : this.configuredCacheNames) {
createAndAddCache(cacheName);
}

this.configuredCacheNames.clear();
}

super.afterPropertiesSet();
}

protected Cache decorateCache(Cache cache) {
if (isCacheAlreadyDecorated(cache)) {
return cache;
}

return super.decorateCache(cache);
}

protected boolean isCacheAlreadyDecorated(Cache cache) {
return ((isTransactionAware()) && (cache instanceof TransactionAwareCacheDecorator));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis 源码 springdata