pom中引入
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
在spring-redis.xml 中加入
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
以及
<!-- redis服务器中心 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="jedisPoolConfig"></property>
<!-- 使用shardInfo是因为项目中使用了shardedJededis -->
<property name="shardInfo" ref="shardInfo"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<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="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
</bean>
<!-- redis缓存管理器 -->
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg ref="redisTemplate"></constructor-arg>
<!-- 类似于一个命名空间的配置 -->
<property name="cacheNames">
<set>
<value>actor</value>
<value>user</value>
<value>account</value>
<value>common</value>
</set>
</property>
<!-- 是否使用前缀 -->
<property name="usePrefix" value="true" />
<!-- 前缀命名,仅当usePrefix为true时才生效 -->
<property name="cachePrefix">
<bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
<constructor-arg name="delimiter" value=":" />
</bean>
</property>
<!-- 默认有效期1h -->
<property name="defaultExpiration" value="1800" />
<!-- 多个缓存有效期,一般的单个工程可以省略此项 -->
<property name="expires">
<map>
<entry key="actor" value="3600" />
<entry key="user" value="3600" />
</map>
</property>
</bean>
<!-- 开启缓存注解 -->
<cache:annotation-driven cache-manager="cacheManager" />
使用自定义注解完成全限定类名+方法名+参数的key生成规则
package com.youyuTech.oneTalkOnline.myAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.cache.annotation.Cacheable;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Cacheable(key = "targetClass+':'+methodName+':'+args")
public @interface MyCacheable {
}
在service中的配置
package com.youyuTech.oneTalkOnline.services.impl;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Tuple;
import com.youyuTech.oneTalkOnline.constant.RedisKeyConstant;
import com.youyuTech.oneTalkOnline.dao.ActorMapper;
import com.youyuTech.oneTalkOnline.model.Actor;
import com.youyuTech.oneTalkOnline.model.User;
import com.youyuTech.oneTalkOnline.model.dto.ActorAndUser;
import com.youyuTech.oneTalkOnline.model.dto.ActorDto;
import com.youyuTech.oneTalkOnline.myAnnotation.MyCacheable;
import com.youyuTech.oneTalkOnline.services.IActorService;
import com.youyuTech.oneTalkOnline.services.IUserService;
@Service
@CacheConfig(cacheNames = "actor")
// 确定命名空间
public class ActorServiceImpl implements IActorService {
private static Logger logger = LoggerFactory.getLogger(ActorServiceImpl.class);
@Resource
private ActorMapper actorMapper;
@Resource
private IUserService userServiceImpl;
@Autowired
private RedisServiceImpl redisService;
// targetClass+methodName+args 类名全限定+方法名+参数
@MyCacheable
public ActorDto loadActorSimpleData(String aid) throws UnsupportedEncodingException {
if (StringUtils.isBlank(aid)) {
throw new NullPointerException("aid should not be null. ");
}
ActorDto aau = new ActorDto();
List<String> actorids = new ArrayList<String>();
actorids.add(aid);
List<Actor> actors = queryActorList(actorids);
Actor actor = actors.isEmpty() ? null : actors.get(0);
User user = userServiceImpl.queryUsersBasicInfo(aid);
if (user != null) {
BeanUtils.copyProperties(user, aau);
}
if (actor != null) {
BeanUtils.copyProperties(actor, aau);
}
return aau;
}
}
root对象的使用
除了上述使用方法参数作为key之外,Spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息。
属性名称 | 描述 | 示例 |
methodName | 当前方法名 | #root.methodName |
method | 当前方法 | #root.method.name |
target | 当前被调用的对象 | #root.target |
targetClass | 当前被调用的对象的class | #root.targetClass |
args | 当前方法参数组成的数组 | #root.args[0] |
caches | 当前被调用的方法使用的Cache | #root.caches[0].name |
当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:
@Cacheable(value={"users", "xxx"}, key="caches[1].name")
public User find(User user) {
returnnull;
}