SpringMVC+redis集群用注解集成,但是@Cacheable无效果

db8726 2018-03-20 01:01:17
ApplicationContext-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">

<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="cacheManager" />

<!-- 引入配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties/redis.properties" />
</bean>

<!-- jedis 配置-->
<bean id="poolConfig" 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="resourcePropertySource" class="org.springframework.core.io.support.ResourcePropertySource">
<constructor-arg name="name" value="redis.properties"/>
<constructor-arg name="resource" value="classpath:properties/redis.properties"/>
</bean>

<!--redisCluster配置-->
<bean id="redisClusterConfiguration" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
<constructor-arg name="propertySource" ref="resourcePropertySource"/>
</bean>

<!-- redis服务器中心 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<constructor-arg name="clusterConfig" ref="redisClusterConfiguration"/>
<constructor-arg name="poolConfig" ref="poolConfig"/>
<property name="password" value="${redis.password}" />
<property name="timeout" value="${redis.timeout}" ></property>
</bean >
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="connectionFactory" />
<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
<property name="keySerializer" >
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer" >
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean >


<!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<!-- 这里可以配置多个redis -->
<bean class="ZhongYan.Cache.RedisCache">
<property name="redisTemplate" ref="redisTemplate" />
<property name="name" value="defaultCache"/>
</bean>
</set>
</property>
</bean>

</beans>

RedisCache.java
public class RedisCache implements Cache {

@Resource
private RedisTemplate<String, Object> redisTemplate;
private String name;

public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}

public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}

public void setName(String name) {
this.name = name;
}

@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}

@Override
public Object getNativeCache() {
// TODO Auto-generated method stub
return this.redisTemplate;
}

@Override
public ValueWrapper get(Object key) {
// TODO Auto-generated method stub
System.out.println("redis get------------------------begin");
final String keyf = (String) key;
Object object = null;
object = redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection)
throws DataAccessException {

byte[] key = keyf.getBytes();
byte[] value = connection.get(key);
if (value == null) {
return null;
}
return toObject(value);

}
});
return (object != null ? new SimpleValueWrapper(object) : null);
}

@Override
public void put(Object key, Object value) {
// TODO Auto-generated method stub
System.out.println("redis put------------------------begin");
final String keyf = (String) key;
final Object valuef = value;
final long liveTime = 86400;

redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] keyb = keyf.getBytes();
byte[] valueb = toByteArray(valuef);
connection.set(keyb, valueb);
if (liveTime > 0) {
connection.expire(keyb, liveTime);
}
return 1L;
}
});
}

/**
* 描述 : <Object转byte[]>. <br>
* <p>
* <使用方法说明>
* </p>
*
* @param obj
* @return
*/
private byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}

/**
* 描述 : <byte[]转Object>. <br>
* <p>
* <使用方法说明>
* </p>
*
* @param bytes
* @return
*/
private Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}

@Override
public void evict(Object key) {
// TODO Auto-generated method stub
final String keyf = (String) key;
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.del(keyf.getBytes());
}
});
}

@Override
public void clear() {
// TODO Auto-generated method stub
redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}

@Override
public <T> T get(Object key, Class<T> type) {
// TODO Auto-generated method stub
return null;
}

@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
// TODO Auto-generated method stub
return null;
}

}

TribeServiceImpl.java
@Service("TribeService")
public class TribeServiceImpl {

@Resource
ExtendDao<TB_MOBILE_TRIBE> extendDao;

@Cacheable(cacheNames = "defaultCache")
public List <Map <String, Object>> GetList(Map <String, Object> map, Map <String, Object> resultMap) throws Exception {
List <TB_MOBILE_TRIBE> list = extendDao.GetList("ZhongYan.Dao.IMobileTribeMapper.GetList", map);
List <Map <String, Object>> mapList = new ArrayList <>();
if (list != null) {
for (TB_MOBILE_TRIBE tmt : list) {
resultMap = new HashMap <>();
resultMap.put("ID", tmt.getID());
resultMap.put("NAME", tmt.getNAME());
resultMap.put("ANNOUNCEMENT", tmt.getANNOUNCEMENT());
resultMap.put("ATT_PATH", tmt.getFile().getATT_PATH());
mapList.add(resultMap);
}
}

return mapList;
}

}
redis.properties
#密码
redis.password=
#最大空闲数
redis.maxIdle=100
#最大连接数
redis.maxActive=300
#最大建立连接等待时间
redis.maxWait=1000
#客户端超时时间单位是毫秒
redis.timeout=100000
redis.maxTotal=1000
redis.minIdle=8
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true

spring.redis.cluster.nodes=10.101.7.174\:6379,10.101.7.174\:6380,10.101.7.174\:6381,10.101.7.174\:6382,10.101.7.174\:6383,10.101.7.174\:6384
spring.redis.cluster.max-redirects=3

tomcat启动有加载redis配置文件的log如下:
2018-03-20 12:48:16 RMI TCP Connection(3)-127.0.0.1 INFO XmlBeanDefinitionReader:317 : Loading XML bean definitions from class path resource [spring/ApplicationContext-redis.xml]


上面大部分代码都是借鉴的,不知道哪出了问题,麻烦大神帮忙看看
...全文
550 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
db8726 2018-03-21
  • 打赏
  • 举报
回复
引用 1 楼 u011594442 的回复:
你先用非注解的方式试试呢~~
我也是下午一点点排查出来 是配置文件的加载顺序问题
Sunyiban 2018-03-20
  • 打赏
  • 举报
回复
你先用非注解的方式试试呢~~

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧