redis 学习笔记(5)-Spring与Jedis的集成
首先不得不服Spring这个宇宙无敌的开源框架,几乎整合了所有流行的其它框架,http://projects.spring.io/spring-data/从这上面看,当下流行的redis、solr、hadoop、mongoDB、couchBase... 全都收入囊中。对于redis整合而言,主要用到的是spring-data-redis
使用步骤:
一、pom添加依赖项
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
其它Spring必备组件,比如Core,Beans之类,大家自行添加吧
观察一下:

jedis、jredis等常用java的redis client已经支持了,不知道以后会不会集成Redisson,spring-data-redis提供了一个非常有用的类:StringRedisTemplate

对于大多数缓存应用场景而言,字符串是最常用的缓存项,用StringRedisTemplate可以轻松应付。
二、spring配置
<bean id="redisSentinelConfiguration"
class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<property name="master">
<bean class="org.springframework.data.redis.connection.RedisNode">
<property name="name" value="mymaster"></property>
</bean>
</property>
<property name="sentinels">
<set>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg index="0" value="10.6.1**.**5" />
<constructor-arg index="1" value="7031" />
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg index="0" value="10.6.1**.**6" />
<constructor-arg index="1" value="7031" />
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg index="0" value="10.6.1**.**1" />
<constructor-arg index="1" value="7031" />
</bean>
</set>
</property>
</bean> <bean id="jedisConnFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg ref="redisSentinelConfiguration" />
</bean> <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnFactory" />
</bean>
提示:上面配置中的端口为sentinel的端口,而非redis-server的端口。
这里我们使用Sentinel模式来配置redis连接,从上篇学习知道,sentinel是一种高可用架构,个人推荐在生产环境中使用sentinel模式。
注:26-28行,经试验,如果修改了默认端口,这里必须明细指定hostName及port,否则运行后,无法正确读写缓存,参考下面的配置:
(2016-4-2更新:最新1.6.4版的spring-data-redis 已经修正了这个问题,无需再指定端口和hostname)
<bean id="jedisConnFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="10.6.53.xxx"/>
<property name="port" value="8830"/>
<property name="usePool" value="false"/>
<constructor-arg ref="redisSentinelConfiguration"/>
</bean>
其中hostName为当前master的IP,port为redis-server的运行端口(非sentinel端口),此外还要设置usePool为false,由于sentinel可能会自行切换master节点,如果不清楚当前的master节点是哪台机器,可以用前面提到的命令./redis-cli -p <sentinal端口号> sentinel masters查看,或者用java代码输出,参考下面的代码:
ApplicationContext ctx = new FileSystemXmlApplicationContext("/opt/app/spring-redis.xml");
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
for (RedisServer m : template.getConnectionFactory().getSentinelConnection().masters()) {
logger.debug(m);
}
另外<property name="usePool" value="false"/> 这里的value值如果改成true,经实际测试,发现偶尔会报如下错误(如果报错,换成false通常就可以了):
redis.clients.jedis.exceptions.JedisDataException: ERR unknown command 'SET'
其它注意事项:
配置文件中的sentinels属性的Set 中的节点,并非一定要在同一个master下,也可以是归属于多个master,即:如果这里配置了10个node信息,其中1-3归属于master1,剩下的4-10属于master2,这也是允许的。
这样调用时,通过StringRedisTemplate.getConnectionFactory().getSentinelConnection().masters()可以返回一个master的列表,然后代码中根据需要,向某一个需要的master写入缓存.
三、单元测试
@Test
public void testSpringRedis() {
ConfigurableApplicationContext ctx = null;
try {
ctx = new ClassPathXmlApplicationContext("spring.xml"); StringRedisTemplate stringRedisTemplate = ctx.getBean("stringRedisTemplate", StringRedisTemplate.class); // String读写
stringRedisTemplate.delete("myStr");
stringRedisTemplate.opsForValue().set("myStr", "http://yjmyzz.cnblogs.com/");
System.out.println(stringRedisTemplate.opsForValue().get("myStr"));
System.out.println("---------------"); // List读写
stringRedisTemplate.delete("myList");
stringRedisTemplate.opsForList().rightPush("myList", "A");
stringRedisTemplate.opsForList().rightPush("myList", "B");
stringRedisTemplate.opsForList().leftPush("myList", "0");
List<String> listCache = stringRedisTemplate.opsForList().range(
"myList", 0, -1);
for (String s : listCache) {
System.out.println(s);
}
System.out.println("---------------"); // Set读写
stringRedisTemplate.delete("mySet");
stringRedisTemplate.opsForSet().add("mySet", "A");
stringRedisTemplate.opsForSet().add("mySet", "B");
stringRedisTemplate.opsForSet().add("mySet", "C");
Set<String> setCache = stringRedisTemplate.opsForSet().members(
"mySet");
for (String s : setCache) {
System.out.println(s);
}
System.out.println("---------------"); // Hash读写
stringRedisTemplate.delete("myHash");
stringRedisTemplate.opsForHash().put("myHash", "PEK", "北京");
stringRedisTemplate.opsForHash().put("myHash", "SHA", "上海虹桥");
stringRedisTemplate.opsForHash().put("myHash", "PVG", "浦东");
Map<Object, Object> hashCache = stringRedisTemplate.opsForHash()
.entries("myHash");
for (Map.Entry<Object, Object> entry : hashCache.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
} System.out.println("---------------"); } finally {
if (ctx != null && ctx.isActive()) {
ctx.close();
}
} }
运行一下,行云流水般的输出:
...
信息: Created JedisPool to master at 10.6.144.***:7030
http://yjmyzz.cnblogs.com/
---------------
0
A
B
---------------
C
B
A
---------------
SHA - 上海虹桥
PVG - 浦东
PEK - 北京
---------------
...
注意红色标出部分,从eclipse控制台的输出,还能看出当前的master是哪台服务器
这里再补充一点小技巧:如果想遍历所有master及slave可以参考以下代码
@Test
public void testGetAllMasterAndSlaves() {
ApplicationContext ctx = new FileSystemXmlApplicationContext("D:/spring-redis.xml");
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
RedisSentinelConnection conn = template.getConnectionFactory().getSentinelConnection();
for (RedisServer m : conn.masters()) {
System.out.println("master => " + m);//打印master信息
Collection<RedisServer> slaves = conn.slaves(m);
//打印该master下的所有slave信息
for (RedisServer s : slaves) {
System.out.println("slaves of " + m + " => " + s);
}
System.out.println("--------------");
}
((FileSystemXmlApplicationContext) ctx).close();
}
输出类似下面的结果:
master => 172.20.16.19:6379
slaves of 172.20.16.19:6379 => 172.20.16.19:6379
注:这里输出的slaves列表,经实际测试,发现只是根据redis server端的配置呆板的返回slave node列表,不管这些node是死是活,换句话说,就算某个slave已经down掉,这里依然会返回。
三、POJO对象的缓存
Spring提供的StringRedisTemplate只能对String操作,大多数情况下已经够用,但如果真需要向redis中存放POJO对象也不难,我们可以参考StringRedisTemplate的源码,扩展出ObjectRedisTemplate
package org.springframework.data.redis.core; import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer; public class ObjectRedisTemplate<T> extends RedisTemplate<String, T> { public ObjectRedisTemplate(RedisConnectionFactory connectionFactory,
Class<T> clazz) { RedisSerializer<T> objectSerializer = new Jackson2JsonRedisSerializer<T>(
clazz); RedisSerializer<String> objectKeySerializer = new Jackson2JsonRedisSerializer<String>(
String.class); setKeySerializer(objectKeySerializer);
setValueSerializer(objectSerializer);
setHashKeySerializer(objectSerializer);
setHashValueSerializer(objectSerializer); setConnectionFactory(connectionFactory);
afterPropertiesSet();
} protected RedisConnection preProcessConnection(RedisConnection connection,
boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}
然后就可以这样用了:
@Test
public void testSpringRedis() {
ConfigurableApplicationContext ctx = null;
try {
ctx = new ClassPathXmlApplicationContext("spring.xml"); JedisConnectionFactory connFactory = ctx.getBean(
"jedisConnFactory", JedisConnectionFactory.class); ObjectRedisTemplate<SampleBean> template = new ObjectRedisTemplate<SampleBean>(
connFactory, SampleBean.class); template.delete("myBean");
SampleBean bean = new SampleBean("菩提树下的杨过");
template.opsForValue().set("myBean", bean); System.out.println(template.opsForValue().get("myBean")); } finally {
if (ctx != null && ctx.isActive()) {
ctx.close();
}
}
}
其中SampleBean的定义如下:
package com.cnblogs.yjmyzz;
import java.io.Serializable;
public class SampleBean implements Serializable {
private static final long serialVersionUID = -303232410998377570L;
private String name;
public SampleBean() {
}
public SampleBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "name:" + name;
}
}
注:由于不是标准的String类型,所以在redis控制台,用./redis-cli get myBean是看不到缓存内容的,只能得到nil的输出,不要误以为set没成功!通过代码是可以正常get到缓存值的。
另外关于POJO对象的缓存,还有二个注意事项:
a) POJO类必须要有默认的无参构造函数,否则反序列化时会报错
b) ObjectRedisTemplate<T>中的T不能是接口,比如 DomainModelA继承自接口 IModelA,使用ObjectRedisTemplate时,要写成ObjectRedisTemplate<DomainModelA>而不是ObjectRedisTemplate<IModelA>,否则反序列化时也会出错
redis 学习笔记(5)-Spring与Jedis的集成的更多相关文章
- redis学习笔记(二)——java中jedis的简单使用
redis怎么在java中使用,那就是要用到jedis了,jedis是redis的java版本的客户端实现,原本原本想上来就直接学spring整合redis的,但是一口吃个胖子,还是脚踏实地,从基础开 ...
- redis 学习笔记(7)-cluster 客户端(jedis)代码示例
上节学习了cluster的搭建及redis-cli终端下如何操作,但是更常用的场景是在程序代码里对cluster读写,这需要redis-client对cluster模式的支持,目前spring-dat ...
- Redis学习笔记(4)—— Jedis入门
一.Jedis介绍 Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持,比如Java.C.C#.C++.php.Node.js.Go等. 在官方网站里列的一些Java客户端,有jedi ...
- Redis学习笔记7--Redis管道(pipeline)
redis是一个cs模式的tcp server,使用和http类似的请求响应协议.一个client可以通过一个socket连接发起多个请求命令.每个请求命令发出后client通常会阻塞并等待redis ...
- redis学习笔记(详细)——高级篇
redis学习笔记(详细)--初级篇 redis学习笔记(详细)--高级篇 redis配置文件介绍 linux环境下配置大于编程 redis 的配置文件位于 Redis 安装目录下,文件名为 redi ...
- redis 学习笔记(6)-cluster集群搭建
上次写redis的学习笔记还是2014年,一转眼已经快2年过去了,在段时间里,redis最大的变化之一就是cluster功能的正式发布,以前要搞redis集群,得借助一致性hash来自己搞shardi ...
- Redis学习笔记~目录
回到占占推荐博客索引 百度百科 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合). ...
- Redis学习笔记4-Redis配置详解
在Redis中直接启动redis-server服务时, 采用的是默认的配置文件.采用redis-server xxx.conf 这样的方式可以按照指定的配置文件来运行Redis服务.按照本Redi ...
- Redis学习笔记一:数据结构与对象
1. String(SDS) Redis使用自定义的一种字符串结构SDS来作为字符串的表示. 127.0.0.1:6379> set name liushijie OK 在如上操作中,name( ...
随机推荐
- 手机屏幕滑动效果框架——flipsnap
下午有时间,研究了下手机网页开发方面的内容.其中关于手机手势滑屏操作.发现有比较好的jquery 插件--flipsnap. 官方网站:http://pxgrid.github.com/js-flip ...
- 自动化部署与统一安装升级 - 类ansible工具 udeploy0.3版本发布 (更新时间2014-12-24)
下载地址: unifyDeploy0.1版本 unifyDeploy0.2版本 unifyDeploy0.3版本 (更新时间2014-07-25) 自动化部署与统一安装升级,适用于多资 ...
- 【转】超实用的JavaScript技巧及最佳实践
众所周知,JavaScript是一门非常流行的编程语言,开发者用它不仅可以开发出炫丽的Web程序,还可以用它来开发一些移动应用程序(如PhoneGap或Appcelerator),它还有一些服务端实现 ...
- Spring为某个属性注入值或为某个方法的返回值
项目中用到需要初始化一些数据,Spring提供了filed的值注入和method的返回值注入. 一.Field值的注入 filed值注入需要使用org.springframework.beans.fa ...
- 源码编译安装screen
OS:Amazon Linux AMI 2015.09.2 (HVM) #sudo su #wget http://ftp.gnu.org/gnu/screen/screen-4.3.1.tar.gz ...
- 用CSS3实现背景的固定
今天放假了,正好最近养成了没事泡泡博客园的习惯,自己也有了博客..不得不吐槽一下博客园为什么页面这么古朴,,带的几个模版也没啥意思,反正不符合我口味,幸亏后台提供了编辑CSS的功能,于是我就搬来现有的 ...
- HTML基础(四)——设置超链接的样式示例
***设置超链接的样式示例 a:link 超链接被点前状态 a:visited 超链接点击后状态 a:hover 悬停在超链接时 a:active 点击超链接时 在定义这些状态时,有一个顺序l v ...
- kill
向一个/一些进程发送一个信号 $kill [-slL] -s指定发送的信号,可以使用名称或者信号编号 -l列出当前系统的所有信号 $kill -l 1) SIGHUP 2) SIGINT 3) SIG ...
- linux添加开机自启动脚本示例详解
linux下(以RedHat为范本)添加开机自启动脚本有两种方法,先来简单的; 一.在/etc/rc.local中添加如果不想将脚本粘来粘去,或创建链接什么的,则:step1. 先修改好脚本,使其所有 ...
- Android 的 Handler 总结
<一> Handler的定义: 主要接受子线程发送的数据, 并用此数据配合主线程更新UI. 解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管 ...