Redis入门很简单之五【Jedis和Spring的整合】
在上一篇文章中,简单介绍了Jedis的连接池使用方式。
如果和Spring进行整合的话,我们将获得更好的简洁性、灵活性,显然是一种更加优雅(graceful)的方式。
[一]. 搭建环境:
1. 在之前版本的基础之上,添加如下的依赖:
spring.jar
commons-logging.jar
log4j-1.2.15.jar
同时添加日志配置文件:log4j.properties到classpath下面。
2. 配置Spring文件:applicationContext.xml
注意:连接池jedisPool的配置,这里使用了构造方式注入,这是和Jedis的API一致的;
在注入port时,需要使用使用type = "int"指定注入的参数类型,否则出现异常。
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
- <!-- 加载redis配置文件 -->
- <context:property-placeholder location="classpath:redis.properties"/>
- <!-- redis连接池的配置 -->
- <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
- <property name="maxActive" value="${redis.pool.maxActive}"/>
- <property name="maxIdle" value="${redis.pool.maxIdle}"/>
- <property name="minIdle" value="${redis.pool.minIdle}"/>
- <property name="maxWait" value="${redis.pool.maxWait}"/>
- <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
- <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
- </bean>
- <!-- redis的连接池pool,不是必选项:timeout/password -->
- <bean id = "jedisPool" class="redis.clients.jedis.JedisPool">
- <constructor-arg index="0" ref="jedisPoolConfig"/>
- <constructor-arg index="1" value="${redis.host}"/>
- <constructor-arg index="2" value="${redis.port}" type="int"/>
- <constructor-arg index="3" value="${redis.timeout}" type="int"/>
- <constructor-arg index="4" value="${redis.password}"/>
- </bean>
- </beans>
[二]. 从SPring容器中获取JedisPool:
- ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
- JedisPool pool = (JedisPool) context.getBean("jedisPool");
- Jedis jedis = pool.getResource();
- ...
- pool.returnResource(jedis);
[三]. 缓存JavaBean:
上一篇文章中,已经有了对Jedis使用的基本说明。
当然很多时候我们都希望Redis能够对JavaBean进行缓存,这需要借助于JDK提供的序列化技术。
1. 要求缓存实体实现了序列化Serializable接口:这里以Userinfo为例。
2. 序列化工具类:Jedis对序列化的支持,是提供了字节数组byte[]作为参数;
为此编写SerializingUtil工具类负责byte[]和JavaBean之间的相互转换。该方法的API如下所示:
- public static byte[] serialize(Object source);
- public static Object deserialize(byte[] source);
该工具类的具体实现:
- /**
- * 功能简述: 序列化工具类,负责byte[]和Object之间的相互转换.
- * @author Nick Xu
- * @version 1.0
- */
- public class SerializingUtil {
- private static Log logger = LogFactory.getLog(SerializingUtil.class);
- /**
- * 功能简述: 对实体Bean进行序列化操作.
- * @param source 待转换的实体
- * @return 转换之后的字节数组
- * @throws Exception
- */
- public static byte[] serialize(Object source) {
- ByteArrayOutputStream byteOut = null;
- ObjectOutputStream ObjOut = null;
- try {
- byteOut = new ByteArrayOutputStream();
- ObjOut = new ObjectOutputStream(byteOut);
- ObjOut.writeObject(source);
- ObjOut.flush();
- }
- catch (IOException e) {
- logger.error(source.getClass().getName()
- + " serialized error !", e);
- }
- finally {
- try {
- if (null != ObjOut) {
- ObjOut.close();
- }
- }
- catch (IOException e) {
- ObjOut = null;
- }
- }
- return byteOut.toByteArray();
- }
- /**
- * 功能简述: 将字节数组反序列化为实体Bean.
- * @param source 需要进行反序列化的字节数组
- * @return 反序列化后的实体Bean
- * @throws Exception
- */
- public static Object deserialize(byte[] source) {
- ObjectInputStream ObjIn = null;
- Object retVal = null;
- try {
- ByteArrayInputStream byteIn = new ByteArrayInputStream(source);
- ObjIn = new ObjectInputStream(byteIn);
- retVal = ObjIn.readObject();
- }
- catch (Exception e) {
- logger.error("deserialized error !", e);
- }
- finally {
- try {
- if(null != ObjIn) {
- ObjIn.close();
- }
- }
- catch (IOException e) {
- ObjIn = null;
- }
- }
- return retVal;
- }
- }
3. 对JavaBean的存储和获取:
定义实体:借助于Timestamp类,获取ms值。
- Userinfo actual = new Userinfo(140520, "Nick Xu",
- new Date(Timestamp.valueOf("1990-11-11 00:00:00").getTime()));
使用Jedis操作:key、value都需要转成byte[]字节数组。
- String key = "user.userid." + actual.getUserId();
- jedis.set(key.getBytes(), SerializingUtil.serialize(actual));
- Userinfo expected = (Userinfo) SerializingUtil.deserialize(jedis.get(key.getBytes()));
对象的比较:需要覆写equals和hashCode方法。
- assertEquals(expected, actual);
顶
踩


参考知识库
- Redis知识库4908 关注 | 738 收录
评论
嗯,是的,稍后会对Spring Data Redis进行介绍,使用起来确实方便 ,不过带来的却是Redis特性的大量丢失
,尤其是,不支持Sharding机制。
都丢失了什么,能例举一下吗?有文章吗?
嗯,是的,稍后会对Spring Data Redis进行介绍,使用起来确实方便 ,不过带来的却是Redis特性的大量丢失
,尤其是,不支持Sharding机制。
Redis入门很简单之五【Jedis和Spring的整合】的更多相关文章
- Redis入门很简单之七【使用Jedis实现客户端Sharding】
Redis入门很简单之七[使用Jedis实现客户端Sharding] 博客分类: NoSQL/Redis/MongoDB redisjedisspringsharding分片 <一>. 背 ...
- Redis入门很简单之六【Jedis常见操作】
Redis入门很简单之六[Jedis常见操作] http://www.tuicool.com/articles/vaqABb http://www.cnblogs.com/stephen-liu74/ ...
- Redis入门很简单之四【初识Jedis】
Redis入门很简单之四[初识Jedis] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存jedis 使用Jedis提供的Java API对Redis进行操作,是Red ...
- Redis入门很简单之一【简介与环境搭建】
Redis入门很简单之一[简介与环境搭建] 博客分类: NoSQL/Redis/MongoDB redisnosqlmemcached缓存中间件 [Redis简介] <一>. NoSQL ...
- Redis入门很简单之三【常见参数配置】
Redis入门很简单之三[常见参数配置] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存中间件memcached Redis的一下常见设置都是通过对redis.conf ...
- Redis入门很简单之二【常见操作命令】
Redis入门很简单之二[常见操作命令] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存 Redis提供了丰富的命令,允许我们连接客户端对其进行直接操作.这里简单介绍一 ...
- Redis入门和Java利用jedis操作redis
Redis入门和Java利用jedis操作redis Redis介绍 Redis 是完全开源的,遵守 BSD 协议,是一个高性能的 key-value 数据库. Redis 与其他 key - val ...
- 踢爆IT劣书出版黑幕——由清华大学出版社之《C语言入门很简单》想到的(1)
1.前言与作者 首先声明,我是由于非常偶然的机会获得<C语言入门很简单>这本书的,绝对不是买的.买这种书实在丢不起那人. 去年这书刚出版时,在CU论坛举行试读推广,我当时随口说了几句(没说 ...
- [电子书] 《Android编程入门很简单》
<Android编程入门很简单>是一本与众不同的Android学习读物,是一本化繁为简,把抽象问题具体化,把复杂问题简单化的书.本书避免出现云山雾罩.晦涩难懂的讲解,代之以轻松活泼.由浅入 ...
随机推荐
- 5 November in 614
Contest A. ssoj2964 交错的士兵 \(n\) 个数的排列,从左到右依次为 1, 2, -, \(n\).\(n\) 次操作,对于第 \(i\) 次操作,从左到右分成很多段,每段 \( ...
- Golang操作MySQL的正确姿势
封装原因: 查看了很多网上提供的ORM类型的数据库操作,觉得比较麻烦,需要提前配置很多的表结构体,然后才能使用,对于数据表很多的项目就配置起来就比较麻烦,所以对golang的mysql包进行了外层包装 ...
- nginx启动、关闭、重启及常用的命令
nginx常用命令 启动:cd /usr/local/nginx/sbin./nginxnginx服务启动后默认的进程号会放在/usr/local/nginx/logs/nginx.pid文件cat ...
- Spring Boot学习一之配置类及自动配置
一.配置类 1. 导入其他配置类 你不需要将所有的 @Configuration 放进一个单独的类, @Import 注解可以用来导入其他配置类.另外,你也可以使用 @ComponentScan 注解 ...
- 【原】通过npm script运行webpack的原理
原理:在项目中,局部安装依赖,依赖如果有创建命令的情况下会在node_modules/.bin目录创建软链接,pack.json默认读取到.bin下的命令. 如有理解不对,请各位大神纠正
- PHP的Session机制解析 2
在鸟哥的博客看到对php session的过期时间的一篇文章,在此记录. 原文地址:http://www.laruence.com/2012/01/10/2469.html 以下是鸟哥博客原文: 今天 ...
- python字符串常用函数-大小写,删除空格,字符串切片
- PAT 2019-3 7-3 Telefraud Detection
Description: Telefraud(电信诈骗) remains a common and persistent problem in our society. In some cases, ...
- 【Python-Django讲义】针对django的ppt讲义
MCV思想: M是指数据模型,V是指用户界面,C则是控制器.使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式.比如一批统计数据你可以分别用柱状图.饼图来表示.C存在的目 ...
- 2019PhpStrom注册码(破解)+汉化(中文)
PhpStrom破解使用 IDEA激活码: https://app.yinxiang.com/fx/bd2158ab-fea3-4382-966f-eaf54f5a4de7 phpStorm使用说明 ...