概述:

   在之前的博客中,有提到过Redis 在服务端的一些相关知识,今天主要讲一下Java 整合Redis的相关内容。

   下面是Jedis 的相关依赖:

    

        <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.5.1</version>
</dependency> <!-- redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>

1、Jedis 单机客户端

   首先我们了解一下,使用Jedis 连接我们的Redis 服务器:

public static void main(String[] args) {
String host = "127.0.0.1";
int port = 6379;
Jedis jedis = new Jedis(host,port,50000);
jedis.set("name","jayce");
String name = jedis.get("name");
System.out.println(name);
jedis.close();
}

  我们先来看直观的运行结果:

 

 1.1 Jedis 构造函数: 

  我们先从Jedis 的构造函数开始说起,在Jedis的源码中,我们可以看到Jedis 提供以下几种构造函数:

  从上图中我们可以看到一个很重要的信息,Jedis 继承BinaryJedis,并且它的所有构造函数都采用了父类的构造函数: 

//根据host 默认端口6379获取连接
public Jedis(final String host) {
super(host);
}
//根据host 与特定端口获取连接
public Jedis(final String host, final int port) {
super(host, port);
}
//根据host 与特定端口获取连接,并且设定key的生命周期
public Jedis(final String host, final int port, final int timeout) {
super(host, port, timeout);
}
//根据JedisShardInfo 配置信息,获取连接
public Jedis(JedisShardInfo shardInfo) {
super(shardInfo);
}
//根据特定URI 获取连接
public Jedis(URI uri) {
super(uri);
}

  我们可以观察到父类BinaryJedis 的构造函数中,最终的目的是为了创建一个client,而这个client实质上是一个connection:

  

   

  因此,我们在创建一个Jedis 对象的过程中,创建了一个对服务器进行连接的Client,而接下来的相关操作,也是由这个client 进行操作。

 1.2 Jedis 的Get和Set:

    在调用Get和Set方法之前,我们需要创建一个连接,然后进行相应的操作,下述代码提供了设置字符串,和设置对象到Redis 中,需要注意的是,我们在将对象放到Redis 之前,需要将对象进行序列化,因此对象需要实现Serializable接口

public static void main(String[] args) {
String host = "127.0.0.1";
int port = 6381;
Jedis jedis = new Jedis(host, port);
setString(jedis);
setObject(jedis);
jedis.close();
} private static void setString(Jedis jedis) {
jedis.set("name", "jayce");
String name = jedis.get("name");
System.out.println(name);
} private static void setObject(Jedis jedis) {
User user = new User();
user.setId(1);
user.setName("jayce");
user.setPassword("kong");
byte[] values = SerializeUtil.serialize(user);
byte[] names = "user".getBytes();
jedis.set(names, values);
byte[] bytes = jedis.get("user".getBytes());
User userCache = (User) SerializeUtil.unserialize(bytes);
System.out.println(userCache); }

   我们在服务器中的Redis 中可以看到:

    数据已经缓存到了Redis 中。

    

    然后,我们再跟踪一下,Jedis 是如何将一个对象存到了服务器中的:

    第一步:Jedis 调用 set 方法,然后调用内部的client进行操作:

public String set(final String key, String value) {
checkIsInMulti();
client.set(key, value);
return client.getStatusCodeReply();
}

   第二步:client 调用 SafeEncoder.encode(key) 方法,将字符串转换成二进制数组,再调用client 中的 set(byte[],byte[])方法:

public void set(final String key, final String value) {
set(SafeEncoder.encode(key), SafeEncoder.encode(value));
} public void set(final byte[] key, final byte[] value) {
sendCommand(Command.SET, key, value);
}

   第三步:在调用父类Connection中的 sendCommand() 方法,最终将内容传到服务器中:

protected Connection sendCommand(final Command cmd, final byte[]... args) {
try {
connect();
Protocol.sendCommand(outputStream, cmd, args);
pipelinedCommands++;
return this;
} catch (JedisConnectionException ex) {
// Any other exceptions related to connection?
broken = true;
throw ex;
}
}

2、Jedis 单机版整合Spring

    在Spring官网中,给出了这样得一个Demo:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="server" p:port="6379" /> </beans>

    这个配置文件比较直接的帮我们配置了 jedisConectionFactory ,我们需要做的是注入这个Bean 之后,在工厂里面获取到Connection,然后进行相应的操作。

    根据常用的场景,我们用到的比较多的是 Pool<Jedis>,因此,这里为大家分享的是JedisPool 的相关配置:

<bean id="redisClient" class="redis.clients.jedis.JedisPool">
<constructor-arg name="host" value="${redis.host}"/>
<constructor-arg name="port" value="${redis.port}"/>
<!--<constructor-arg name="poolConfig" ref="jedisPoolConfig"/>-->
</bean>

    

  接下来我们研究一下,JedisPool 的源码,方便我们对配置文件的理解:

public JedisPool(GenericObjectPoolConfig poolConfig, String host) {
this(poolConfig, host, 6379, 2000, (String)null, 0, (String)null);
} public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port, 2000, (String)null, 0, (String)null);
} public JedisPool(String host) {
URI uri = URI.create(host);
if(uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost();
int port = uri.getPort();
String password = uri.getUserInfo().split(":", 2)[1];
int database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
this.internalPool = new GenericObjectPool(new JedisFactory(h, port, 2000, password, database, (String)null), new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool(new JedisFactory(host, 6379, 2000, (String)null, 0, (String)null), new GenericObjectPoolConfig());
} } public JedisPool(URI uri) {
String h = uri.getHost();
int port = uri.getPort();
String password = uri.getUserInfo().split(":", 2)[1];
int database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
this.internalPool = new GenericObjectPool(new JedisFactory(h, port, 2000, password, database, (String)null), new GenericObjectPoolConfig());
} public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port, int timeout, String password) {
this(poolConfig, host, port, timeout, password, 0, (String)null);
} public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port) {
this(poolConfig, host, port, 2000, (String)null, 0, (String)null);
} public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port, int timeout) {
this(poolConfig, host, port, timeout, (String)null, 0, (String)null);
} public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port, int timeout, String password, int database) {
this(poolConfig, host, port, timeout, password, database, (String)null);
} public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port, int timeout, String password, int database, String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password, database, clientName));
}

    

    JedisPool 的构造函数与上述的Jedis 的构造函数很相似,这里比较特别的是 GenericObjectPoolConfig 这个配置类,这个类 是org.apache.commons.pool2 包下面的一个用来设置池的大小的类

    我们在配置application.xml文件的时候,可以自己配置对应的池大小,但是如果没有相应的配置文件的同学,推荐还是使用默认配置。

public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-Redis.xml");
Pool<Jedis> jedisPool = (Pool)applicationContext.getBean("redisClient");
Jedis jedis = jedisPool.getResource();
setString(jedis);
setObject(jedis);
jedisPool.returnResource(jedis);
} private static void setString(Jedis jedis) {
jedis.set("name", "jayce");
String name = jedis.get("name");
System.out.println(name);
} private static void setObject(Jedis jedis) {
User user = new User();
user.setId(1);
user.setName("jayce");
user.setPassword("kong");
byte[] values = SerializeUtil.serialize(user);
byte[] names = "user".getBytes();
jedis.set(names, values);
byte[] bytes = jedis.get("user".getBytes());
User userCache = (User) SerializeUtil.unserialize(bytes);
System.out.println(userCache); }

    运行结果:

jayce
User{id=1, name='jayce', password='kong'}

3、总结

    项目源码:https://github.com/jaycekon/Crawl-Page

    后面会继续总结,Spring 整合 Redis 集群~

深入浅出Redis-Spring整合Redis的更多相关文章

  1. 网站性能优化小结和spring整合redis

    现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...

  2. Spring整合Redis&JSON序列化&Spring/Web项目部署相关

    几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...

  3. spring整合redis之hello

    1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...

  4. Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object

    我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!

  5. Redis的安装以及spring整合Redis时出现Could not get a resource from the pool

    Redis的下载与安装 在Linux上使用wget http://download.redis.io/releases/redis-5.0.0.tar.gz下载源码到指定位置 解压:tar -xvf ...

  6. Spring整合redis实现key过期事件监听

    打开redis服务的配置文件   添加notify-keyspace-events Ex  如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...

  7. (转)Spring整合Redis作为缓存

           采用Redis作为Web系统的缓存.用Spring的Cache整合Redis. 一.关于redis的相关xml文件的写法 <?xml version="1.0" ...

  8. spring整合redis客户端及缓存接口设计(转)

    一.写在前面 缓存作为系统性能优化的一大杀手锏,几乎在每个系统或多或少的用到缓存.有的使用本地内存作为缓存,有的使用本地硬盘作为缓存,有的使用缓存服务器.但是无论使用哪种缓存,接口中的方法都是差不多. ...

  9. spring整合redis使用RedisTemplate的坑Could not get a resource from the pool

    一.背景 项目中使用spring框架整合redis,使用框架封装的RedisTemplate来实现数据的增删改查,项目上线后,我发现运行一段时间后,会出现异常Could not get a resou ...

  10. spring整合redis(哨兵模式)

    首先服务器搭建哨兵模式(我这里使用的是Windows8系统),感谢两位博主,少走不少弯路,在此给出链接:服务器哨兵模式搭建和整合哨兵模式 什么一些介绍就不介绍了,可以看一下连接,比较详细,初次接触,当 ...

随机推荐

  1. Linux服务器开发/测试环境搭建-流程

    1.MariaDB yum 安装/初始化/授远程权限 yum安装 在MariaDB官网根据Linux系统查找您所需要的db版本:https://downloads.mariadb.org/mariad ...

  2. css所有属性参考

    学习地址:https://developer.mozilla.org/zh-CN/docs/Web/CSS/Reference

  3. 搭建自己的BT下载平台服务器

    [原理基础] BT(Bit Torren比特流)是由国外的一名叫Bram Cohen的程序员开发的下载软件,可以说它是目前网络是非常流行的一个多点下载的P2P软件,它最显著的特点就是:下载的人越多,速 ...

  4. windows svn利用钩子实现代码同步到web目录

    思路:  找 到SVN Server中的仓库(Repositories)文件夹的位置,在相应的项目文件夹中找到hooks文件夹.在该文件夹中添加一个post- commit文件:当有commit动作发 ...

  5. js原生设计模式——3简单工厂模式\js面向对象编程实例

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  6. ASP.NET MVC和jQuery DataTable整合

    本文包含代码示例说明如何jQuery插件开发者可以集成到ASP.NET MVC应用程序. 下载源代码- 87.4 KB Introduction The jQuery DataTables plug- ...

  7. 基于Doubango的iOS客户端开源框架

    一.ios-ngn-statck工程 1.Tests ---功能测试 2.底层模块(c和c++) Doubango --- 基于3GPP IMS/RCS 并能用于嵌入式和桌面系统的开源框架 1) ti ...

  8. Codeforces758C

    C. Unfair Poll time limit per test:1 second memory limit per test:256 megabytes input:standard input ...

  9. Linux 用键盘操作窗口

    以下是我从各处搜集来的关于用键盘操作窗口信息,操作可能不是最简或者最好的,当然也可能不是最全的,以后遇到新的操作,我会即使添加,如果你有我没有列出的操作,希望你能提出,我可以加上! 我实验的操作系统是 ...

  10. loadrunner动态从mysql取值

    loadrunner动态从mysql取值 [需要下载跟数据库服务器一致的dll,32位或64位] loadrunner中有参数化从数据库中取值,但是只是静态的,对于一些要实时取值的数据就game ov ...