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"指定注入的参数类型,否则出现异常。

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:context="http://www.springframework.org/schema/context"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  5. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  6. <!-- 加载redis配置文件 -->
  7. <context:property-placeholder location="classpath:redis.properties"/>
  8. <!-- redis连接池的配置 -->
  9. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  10. <property name="maxActive" value="${redis.pool.maxActive}"/>
  11. <property name="maxIdle" value="${redis.pool.maxIdle}"/>
  12. <property name="minIdle" value="${redis.pool.minIdle}"/>
  13. <property name="maxWait" value="${redis.pool.maxWait}"/>
  14. <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
  15. <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
  16. </bean>
  17. <!-- redis的连接池pool,不是必选项:timeout/password  -->
  18. <bean id = "jedisPool" class="redis.clients.jedis.JedisPool">
  19. <constructor-arg index="0" ref="jedisPoolConfig"/>
  20. <constructor-arg index="1" value="${redis.host}"/>
  21. <constructor-arg index="2" value="${redis.port}" type="int"/>
  22. <constructor-arg index="3" value="${redis.timeout}" type="int"/>
  23. <constructor-arg index="4" value="${redis.password}"/>
  24. </bean>
  25. </beans>

[二]. 从SPring容器中获取JedisPool:

  1. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  2. JedisPool pool = (JedisPool) context.getBean("jedisPool");
  3. Jedis jedis = pool.getResource();
  4. ...
  5. pool.returnResource(jedis);

[三]. 缓存JavaBean:
 上一篇文章中,已经有了对Jedis使用的基本说明。

当然很多时候我们都希望Redis能够对JavaBean进行缓存,这需要借助于JDK提供的序列化技术。
   1. 要求缓存实体实现了序列化Serializable接口:这里以Userinfo为例。
   2. 序列化工具类:Jedis对序列化的支持,是提供了字节数组byte[]作为参数;
  为此编写SerializingUtil工具类负责byte[]和JavaBean之间的相互转换。该方法的API如下所示:

  1. public static byte[] serialize(Object source);
  2. public static Object deserialize(byte[] source);

该工具类的具体实现:

  1. /**
  2. * 功能简述: 序列化工具类,负责byte[]和Object之间的相互转换.
  3. * @author Nick Xu
  4. * @version 1.0
  5. */
  6. public class SerializingUtil {
  7. private static Log logger = LogFactory.getLog(SerializingUtil.class);
  8. /**
  9. * 功能简述: 对实体Bean进行序列化操作.
  10. * @param source 待转换的实体
  11. * @return 转换之后的字节数组
  12. * @throws Exception
  13. */
  14. public static byte[] serialize(Object source) {
  15. ByteArrayOutputStream byteOut = null;
  16. ObjectOutputStream ObjOut = null;
  17. try {
  18. byteOut = new ByteArrayOutputStream();
  19. ObjOut = new ObjectOutputStream(byteOut);
  20. ObjOut.writeObject(source);
  21. ObjOut.flush();
  22. }
  23. catch (IOException e) {
  24. logger.error(source.getClass().getName()
  25. + " serialized error !", e);
  26. }
  27. finally {
  28. try {
  29. if (null != ObjOut) {
  30. ObjOut.close();
  31. }
  32. }
  33. catch (IOException e) {
  34. ObjOut = null;
  35. }
  36. }
  37. return byteOut.toByteArray();
  38. }
  39. /**
  40. * 功能简述: 将字节数组反序列化为实体Bean.
  41. * @param source 需要进行反序列化的字节数组
  42. * @return 反序列化后的实体Bean
  43. * @throws Exception
  44. */
  45. public static Object deserialize(byte[] source) {
  46. ObjectInputStream ObjIn = null;
  47. Object retVal = null;
  48. try {
  49. ByteArrayInputStream byteIn = new ByteArrayInputStream(source);
  50. ObjIn = new ObjectInputStream(byteIn);
  51. retVal = ObjIn.readObject();
  52. }
  53. catch (Exception e) {
  54. logger.error("deserialized error  !", e);
  55. }
  56. finally {
  57. try {
  58. if(null != ObjIn) {
  59. ObjIn.close();
  60. }
  61. }
  62. catch (IOException e) {
  63. ObjIn = null;
  64. }
  65. }
  66. return retVal;
  67. }
  68. }

3. 对JavaBean的存储和获取:
        定义实体:借助于Timestamp类,获取ms值。

  1. Userinfo actual = new Userinfo(140520, "Nick Xu",
  2. new Date(Timestamp.valueOf("1990-11-11 00:00:00").getTime()));

使用Jedis操作:key、value都需要转成byte[]字节数组。

  1. String key = "user.userid." + actual.getUserId();
  2. jedis.set(key.getBytes(), SerializingUtil.serialize(actual));
  3. Userinfo expected = (Userinfo) SerializingUtil.deserialize(jedis.get(key.getBytes()));

对象的比较:需要覆写equals和hashCode方法。

  1. assertEquals(expected, actual);
0 
0 
分享到:  
参考知识库
Redis知识库4908  关注 | 738  收录
评论
5 楼 di1984HIT 2017-02-02  
慢慢会完善很多。罗马不是一日建成
4 楼 alafqq 2016-05-20  
希望楼主提供完整的代码~~哈哈jredis.properties
3 楼 19774279 2015-07-31  
Hello_Nick_Xu 写道
yixiandave 写道
Spring不是有一个Spring-data-redis的项目吗??

嗯,是的,稍后会对Spring Data Redis进行介绍,使用起来确实方便 ,不过带来的却是Redis特性的大量丢失 ,尤其是,不支持Sharding机制。

都丢失了什么,能例举一下吗?有文章吗?

2 楼 Hello_Nick_Xu 2014-06-08  
yixiandave 写道
Spring不是有一个Spring-data-redis的项目吗??

嗯,是的,稍后会对Spring Data Redis进行介绍,使用起来确实方便 ,不过带来的却是Redis特性的大量丢失 ,尤其是,不支持Sharding机制。 

Redis入门很简单之五【Jedis和Spring的整合】的更多相关文章

  1. Redis入门很简单之七【使用Jedis实现客户端Sharding】

    Redis入门很简单之七[使用Jedis实现客户端Sharding] 博客分类: NoSQL/Redis/MongoDB redisjedisspringsharding分片 <一>. 背 ...

  2. Redis入门很简单之六【Jedis常见操作】

    Redis入门很简单之六[Jedis常见操作] http://www.tuicool.com/articles/vaqABb http://www.cnblogs.com/stephen-liu74/ ...

  3. Redis入门很简单之四【初识Jedis】

    Redis入门很简单之四[初识Jedis] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存jedis  使用Jedis提供的Java API对Redis进行操作,是Red ...

  4. Redis入门很简单之一【简介与环境搭建】

    Redis入门很简单之一[简介与环境搭建] 博客分类: NoSQL/Redis/MongoDB redisnosqlmemcached缓存中间件  [Redis简介] <一>. NoSQL ...

  5. Redis入门很简单之三【常见参数配置】

    Redis入门很简单之三[常见参数配置] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存中间件memcached  Redis的一下常见设置都是通过对redis.conf ...

  6. Redis入门很简单之二【常见操作命令】

    Redis入门很简单之二[常见操作命令] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存  Redis提供了丰富的命令,允许我们连接客户端对其进行直接操作.这里简单介绍一 ...

  7. Redis入门和Java利用jedis操作redis

    Redis入门和Java利用jedis操作redis Redis介绍 Redis 是完全开源的,遵守 BSD 协议,是一个高性能的 key-value 数据库. Redis 与其他 key - val ...

  8. 踢爆IT劣书出版黑幕——由清华大学出版社之《C语言入门很简单》想到的(1)

    1.前言与作者 首先声明,我是由于非常偶然的机会获得<C语言入门很简单>这本书的,绝对不是买的.买这种书实在丢不起那人. 去年这书刚出版时,在CU论坛举行试读推广,我当时随口说了几句(没说 ...

  9. [电子书] 《Android编程入门很简单》

    <Android编程入门很简单>是一本与众不同的Android学习读物,是一本化繁为简,把抽象问题具体化,把复杂问题简单化的书.本书避免出现云山雾罩.晦涩难懂的讲解,代之以轻松活泼.由浅入 ...

随机推荐

  1. soj#547 bzoj5046 分糖果游戏

    分析 代码 #include<bits/stdc++.h> using namespace std; #define int long long ; ][],s[],p[],v[]; si ...

  2. 【转】 Linux 命令解释(Linux基础二)

    前言 对服务器来讲,图形界面会占用更多的系统资源,而且会安装更多的服务.开放更多的端口,这对服务器的稳定性和安全性都有负面影响.其实,服务器是一个连显示器都没有的家伙,要图形界面干十么? 说到这里,有 ...

  3. 建站手册-网站建设:Web 安全

    ylbtech-建站手册-网站建设:Web 安全 1.返回顶部 1. http://www.w3school.com.cn/site/site_security.asp 2. 2.返回顶部 1. 此刻 ...

  4. ajax请求controller出现中文乱码

    ajax请求controller出现中文乱码 解决方法:在 @RequestMapping 中加上  produces = {"application/json;charset=UTF-8& ...

  5. 箫声远(本人)的小站(为展示作品、简历,基于github pages)

    箫声远的个人前端小站在线地址

  6. selenium:Xpath定位详解

    xpath定位在业界被戏称为元素定位的"屠龙宝刀",宝刀在手,武林我有.现在我们就来详解xpath定位方法. 一.xpath通过元素属性定位 xpath可以通过元素的属性来定位,如 ...

  7. C语言|博客作业6

    一.本周教学内容&目标 第3章 分支结构 3.1-3.2 使学生熟悉多分支结构.字符型数据类型和逻辑运算符. 二.本周作业头 问题 答案 这个作业属于那个课程 C语言程序设计II 这个作业要求 ...

  8. LeetCode6 dp

    120. Triangle 我的解法用了一个二维数组,这样比较浪费空间.O(n*n) 但是标准答案自底向上,一是不需要进行特别判断,二是可以覆盖数组,则只需要O(n)的空间大小. class Solu ...

  9. inno setup静默安装

    [Code] //关键代码静默安装 procedure InitializeWizard(); begin   //不显示边框,这样就能达到不会闪两下了   WizardForm.BorderStyl ...

  10. ubantu下关于linux命令合集

    ubantu下linux的命令与操作 1.熟悉linux目录是学习linux非常必要的第一步 linux目录结构: linux目录: /:根目录,一般根目录下只存放目录,在Linux下有且只有一个根目 ...