RedisTemplate使用场景
设置key的失效时间
通过RedisTemplate可以很方便的操作ZCache来设置某个key的失效时间。
//用redisTemplate设置key失效时间
@Test
public void testExpire() {
Boolean expire = redisTemplate.expire("Billing:AcctItemTypeDto:code:Test", 10000, TimeUnit.SECONDS);
Long time = redisTemplate.getExpire("Billing:AcctItemTypeDto:code:Test");
Assert.assertTrue(time <= 10000);
}
原子计数器
通过RedisTemplate获取ValueOperations接口可以很方便的操作ZCache实现原子计数器功能。
//用valueOps做原子计数
@Test
public void testIncrement() {
redisTemplate.delete("Test:Increment");
Long value = valueOps.increment("Test:Increment", 1);
Assert.assertTrue(value == 1);
}
保留最新的N条记录
通过RedisTemplate获取ListOperations接口可以很方便的操作ZCache中List类型数据,将数据放到List中,通过trim调用,可以保留相应数据。
//用listOps保留最新的N条记录
@Test
public void testRecentN() {
final String key = "Test:RecentN";
redisTemplate.delete(key);
for(int i = 0; i < 15; i++) {
listOps.leftPush(key, "recent " + i);
}
listOps.trim(key, 0, 9);
List<String> list = listOps.range(key, 0, 9);
for(String str : list) {
System.out.println(str);
}
Assert.assertTrue(listOps.size(key) == 10);
}
数据排重统计
通过RedisTemplate获取SetOperations接口可以很方便的操作ZCache中Set类型数据,将数据放到Set中,会自动过滤掉重复的数据。
//用setOps测试去重
@Test
public void testUnrepeated() {
final String key = "Test:Unrepeated";
redisTemplate.delete(key);
setOps.add(key, "bob", "john", "john", "smith");
Set<String> members = setOps.members(key);
for(String str : members) {
System.out.println(str);
}
Assert.assertTrue(members.size() == 3);
}
排行榜取Top N
通过RedisTemplate获取ZSetOperations接口可以很方便的操作ZCache中SortedSet类型数据,将数据放到SortedSet中,会按照指定字段进行排序,通过相应方法获取对象的排名和分值。
//用zSetOps测试Top N
@Test
public void testTopN() {
final String key = "Test:TopN";
redisTemplate.delete(key);
zSetOps.add(key, "bob", 87);
zSetOps.add(key, "john", 89);
zSetOps.add(key, "smith", 86);
zSetOps.add(key, "oracle", 83);
zSetOps.add(key, "mysql", 90);
Set<String> range = zSetOps.reverseRange(key, 0, 2);
for(String str : range) {
Double score = zSetOps.score(key, str);
System.out.println(str + ":" + score);
}
Assert.assertTrue(range.toArray(new String[3])[0].equals("mysql"));
}
缓存ProtoBuf协议对象
可以使用RedisTemplate来操作protobuf协议对象的存取,注意必须禁用其默认的序列化方式。配置RedisTemplate如下:
private static final String PREFIX = "proto.cache";
@Bean
@ConfigurationProperties(prefix = PREFIX)
public ZCacheClientConfig protoZCacheClientConfig() {
return new ZCacheClientConfig();
}
@Bean
@ConditionalOnProperty(prefix = PREFIX, value = "enabled", matchIfMissing = true)
public DefaultZCacheClient protoZCacheClient() {
return new DefaultZCacheClient(protoZCacheClientConfig());
}
@Bean
@ConditionalOnProperty(prefix = PREFIX, value = "redis-enabled", matchIfMissing = true)
public RedisConnectionFactory protoRedisConnectionFactory() {
return new ZCacheJedisConnectionFactory(protoZCacheClient());
}
//定义专门用于操作ProtoBuf协议的RedisTemplate
@Bean
public <K, V> RedisTemplate<K, V> protoRedisTemplate() {
RedisTemplate<K, V> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(protoRedisConnectionFactory());
redisTemplate.setKeySerializer(new ZCacheKeyRedisSerializer()); //建议使用我们的key的序列化方式
redisTemplate.setHashKeySerializer(new ZCacheKeyRedisSerializer());//建议使用我们的key的序列化方式
redisTemplate.setEnableDefaultSerializer(false); //必须禁用默认的序列化方式
return redisTemplate;
}
//定义用于一般缓存操作的RedisTemplate,如注解式缓存、编程式缓存,注意其不支持ProtoBuf
@Bean
public <K, V> RedisTemplate<K, V> redisTemplate() {
RedisTemplate<K, V> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(protoRedisConnectionFactory());
redisTemplate.setKeySerializer(new ZCacheKeyRedisSerializer());
redisTemplate.setHashKeySerializer(new ZCacheKeyRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
//定义用于一般操作的cacheManager,更多配置请参考ProductionZCacheConfiguration
@Bean
public CacheManager cacheManager() {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
cacheManager.setUsePrefix(true);
return cacheManager;
}
使用如下:
@Resource(name="protoRedisTemplate")
private ValueOperations<String, byte[]> valueOps;
@Test
public void testValueOps() throws InvalidProtocolBufferException {
TestBufProto.TestBuf.Builder builder = TestBufProto.TestBuf.newBuilder();
builder.setID( 123 );
builder.setUrl("http://www.21cn.com");
TestBufProto.TestBuf info = builder.build();
byte[] buf = info.toByteArray();
valueOps.set("ftf:TestBuf:123", buf);
byte[] bytes = valueOps.get("ftf:TestBuf:123");
TestBufProto.TestBuf tb = TestBufProto.TestBuf.parseFrom(bytes);
Assert.assertEquals(info.getID(), tb.getID());
Assert.assertEquals(info.getUrl(), tb.getUrl());
}