redis入门很简单之五jedis和spring的整合

     2022-03-22     376

关键词:

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

Xml代码  技术分享
  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.     
  7.       <!-- 加载redis配置文件 -->  
  8.       <context:property-placeholder location="classpath:redis.properties"/>  
  9.         
  10.       <!-- redis连接池的配置 -->  
  11.       <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  12.           <property name="maxActive" value="${redis.pool.maxActive}"/>  
  13.           <property name="maxIdle" value="${redis.pool.maxIdle}"/>  
  14.           <property name="minIdle" value="${redis.pool.minIdle}"/>  
  15.           <property name="maxWait" value="${redis.pool.maxWait}"/>  
  16.           <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>  
  17.           <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>  
  18.       </bean>  
  19.         
  20.       <!-- redis的连接池pool,不是必选项:timeout/password  -->  
  21.       <bean id = "jedisPool" class="redis.clients.jedis.JedisPool">  
  22.           <constructor-arg index="0" ref="jedisPoolConfig"/>  
  23.           <constructor-arg index="1" value="${redis.host}"/>  
  24.           <constructor-arg index="2" value="${redis.port}" type="int"/>  
  25.           <constructor-arg index="3" value="${redis.timeout}" type="int"/>  
  26.           <constructor-arg index="4" value="${redis.password}"/>  
  27.       </bean>  
  28.         
  29.   </beans>  

 

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

Java代码  技术分享
  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如下所示:

Java代码  技术分享
  1. public static byte[] serialize(Object source);   
  2. public static Object deserialize(byte[] source);  

   该工具类的具体实现:

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

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

Java代码  技术分享
  1. Userinfo actual = new Userinfo(140520, "Nick Xu",   
  2. new Date(Timestamp.valueOf("1990-11-11 00:00:00").getTime()));  

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

Java代码  技术分享
  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方法。   

Java代码  技术分享
  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机制。 


















06005_jedis入门

1、Jedis介绍  (1)Redis不仅是使用命令来操作。现在基本上主流的语言都有客户端支持,比如Java、C、C#、C++、PHP、Node.js、Go等;  (2)在官方网站里列有一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis等,其中官方推荐... 查看详情

springdataredis操作redis简单案例

...ata-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(J 查看详情

jedis入门及对redis数据结构的操作(代码片段)

文章目录Jedis简介及其入门Jedis简介Jedis的操作入门Jedis操作Redis中的数据结构字符串类型:string哈希类型:map列表类型:list集合类型:set有序集合类型:sortedsetJedis简介及其入门Jedis简介redis是当今基本所有互联... 查看详情

spring-boot使用jedis操作redis

背景:  1.Redis之前学了个皮毛还忘的差不多了,感觉公司项目中的Redis用的真的牛逼,so需要深造。  2.有个同事在搞Jedis,勾起了我对知识的向往,不会用,但是很渴望。过程:  1.改造原有项目集成Jedis,引入jar包<depe... 查看详情

redis入门

packagecom.nanrenld.jedis;importorg.junit.Test;importredis.clients.jedis.Jedis;importredis.clients.jedis.JedisPool;importredis.clients.jedis.JedisPoolConfig;/***Jedis测试*@authorAdministrator**/publiccl 查看详情

spring-data-redis2.0的使用

...发现百度不到顺手的文档,搞通后发现其实这个过程非常简单和简洁,觉得有必要拿出来分享一下。SpringBoot2.x不再使用Jedis,换成了Lettuce。Lettuce是基于Netty实现的,所以性能更好。但是我看到很多文章居然在SpringBoot2.x还在写Jedi... 查看详情

spring-data-redis和jedis版本对应收集总结

基于spring主版本为4.3.13.RELEASE的项目,测试以下对应版本可用。spring-data-redis版本jedis版本备注1.5.2.RELEASE2.7.3 1.6.0.RELEASE2.7.2 2.7.3 1.6.2.RELEASE2.8.0 1.8.1.RELEASE2.9.0 1.8.4.RELEASE2.9.0   查看详情

redis入门详解之五种基本数据结构

目录一、背景二、redis的五种数据类型2.1字符串类型2.1.1基本介绍2.1.2命令2.1.2.1赋值和取值2.1.2.2递增数字2.1.3实践2.1.3.1统计访问量2.1.3.2生成自增ID2.1.3.3存储对象2.1.4命令拾遗2.1.4.1incrby增加指定整数2.1.4.2decr减少整数2.1.4.3incrbyfloat... 查看详情

java中jedis操作redis与spring的整合

Redis是一个key-value存储系统。它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)和zset(有序集合)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在... 查看详情

spring集成redis客户端jedis(java)

jedis是redis的java客户端,spring将redis连接池作为一个bean配置。“redis.clients.jedis.JedisPool”,这是单机环境适用的redis连接池。 1、maven导入相关包:<!--redis依赖包--><dependency><groupId>redis.clients</groupId>&l 查看详情

在java中使用redis

在java中使用redis很简单,只需要添加jedist.jar,通过它的api就可以了。而且,api和redis的语法几乎完全相同。以下简单的测试:参考:http://www.runoob.com/redis/redis-java.html1packagecom.test.redis;23importorg.junit.Test;4importredis.clients.jedis.Jedis; 查看详情

jedis入门教程(代码片段)

1jedis介绍2java连接Redis1导入jar包2连接实例@Test//获得单一的jedis对象操作数据库publicvoidtest1()//1、获得连接对象设置ip地址和端口Jedisjedis=newJedis("192.168.204.128",6379);//2、设置数据jedis.set("name","zhangsan");//3获得数据Stringname=jedis.get("name")... 查看详情

无法为 Spring 数据 redis 获取 redisTemplate 的连接

...Jedis使用Spring数据Redis将消息发布到通道。这是一个非常简单的Java配置:@Bean(name="jedisConnectionFactory")Jedis 查看详情

spring入门之五-------springioc之通过注解实现

一、准备工作创建一个Class注解@Configuration,如下例子:@Configuration//该注解可理解为将当前class等同于一个xml文件@ComponentScan("com.imooc.springClass5.annotation")//开启包扫描publicclassBeanConfiguration{}我们创建了一个Class(类名可随意)并注... 查看详情

ssm整合redis

...等操作,用过的人应该知道,Jedis客户端已经足够简单和轻量级了,但是呢,在此同时,Spring也为Redis提供了支持,就是在Spring-data模块中的Spring-Data-Redis(SDR),它一部分是基于Jedis客户端的API... 查看详情

redis的java客户端jedis的八种调用方式(事务管道分布式)介绍

...在这里对jedis关于事务、管道和分布式的调用方式做一个简单的介绍和对比:一、普通同步方式最简单和基础的调用方式:1@Test2publicvoidtest1Normal(){3Jedisjedis=newJedis("localhost") 查看详情

jedis如何支持sentinel

...,初始化Sentinel和Pool。我们先看看initSentinel。方法很长,简单说说逻辑:看看这个线程的主要内容:该方法已经写了很多注释,稍微说下逻辑:根据哨兵的host和port创建一个jedis对象,然后,这个jedis对象订阅了pub/sub消息,,消... 查看详情

java调用redis的八种方式

...在这里对jedis关于事务、管道和分布式的调用方式做一个简单的介绍和对比:一、普通同步方式最简单和基础的调用方式@Testpublicvoidtest1Normal(){Jedisjedis=newJedis("localhost");lon 查看详情