spring cache redis 使用
最近在用redis 做缓存开发,觉得自己写接口很麻烦, 看到spring 提供了 redis 缓存, 记录之
1. 使用的是最近的spring 包 4.1.6.RELEASE, spring data redis 1.5.0.RELEASE 和jedis client 2.6.2, 使用maven 构建
2, redis 安装就不说了, 很简单。 下面是简单的配置文件, redis 分片和 池 的使用就自行定义了
<cache:annotation-driven cache-manager="cacheManager"/> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${jedis.host}" /> <property name="port" value="${jedis.port}"/> <property name="usePool" value="true" /> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg index="0" ref="redisTemplate" /> </bean>
两个简单的类, bean 和 service
public class CacheUser implements Serializable{ private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
@Service public class UserService { private CacheUser user; @Cacheable(value="cacheUserList") public List<CacheUser> list() { List<CacheUser> list=new ArrayList<>(); for (int i = 0; i < 10; i++) { user=new CacheUser(); user.setUsername("username"+i); user.setPassword("password"+i); list.add(user); } System.out.println("==get from java=="+System.nanoTime()); return list; } }
测试junit 4
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring-cache.xml") public class CacheTest { @Inject private UserService us; @Test public void test(){ System.out.println(us.list()); System.out.println(us.list()); } }
可以看到输出一次 == get from jave == 和两次列表, 说明数据已存储到redis .
附 spring cache 注解的使用
spring cache 有两个主要注解 @Cacheable (负责将方法的返回值加入到缓存中), @CacheEvict(清除缓存)
@Cacheable :
value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL
@CacheEvict:
value:缓存位置名称,不能为空,同上
key:缓存的key,默认为空,同上
condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
allEntries:true表示清除value中的全部缓存,默认为false