楔子
在使用spring和redis。
想根据不同的业务类型选择不同的数据库
实现
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
JedisConnectionFactory connectionFactory;
ValueOperations<String, String> opsForValue;
/**
*选择redis数据库
*/
protected void selRedisDB() {
connectionFactory.setDatabase(RedisDataBase.REDIS_DB_BLOG);
stringRedisTemplate.setConnectionFactory(connectionFactory);
}
## 使用
/**
* 操作redis中的博客,type为空表示删除博客
*
* @param blog
* @param type
*/
protected void saveBlogToRedis(BlogArticleWithBLOBs blog, int type) {
opsForValue = stringRedisTemplate.opsForValue();
selRedisDB();
if (StringUtils.isEmpty(type)) {
delBlogToRedis(blog.getId());
} else {
opsForValue = stringRedisTemplate.opsForValue();
opsForValue.set(RedisDataBase.KEY_BLOG_ARTICLE + blog.getId(), JSON.toJSONString(blog));
}
}
spring中Redis简单配置
<!-- redis配置开始 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!--redis连接类 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<!--泛型redis模板类 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<!-- 字符型redis模板类 -->
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<!-- redis配置结束 -->
后记
此处只是简单的使用记录