jedis入门一

一.下载Jedis的依赖包jedis-2.1.0.jar,然后将其添加到classpath下面。

1. 定义连接:Redis暂时不要设置登录密码

Jedis jedis = new Jedis("192.168.142.12");

2. 进行键值存储:

jedis.set("country", "China");

3. 获取value值:

String country = jedis.get("country");

4. 删除key:

jedis.del("country");

二、使用连接池: 

1. 添加依赖包commons-pool.jar,注意不要选择高版本,以免不必要的错误。 
 2. 配置属性文件:redis.properties

redis.host=192.168.142.12   	 #Redis服务器地址
redis.port=6379        		 #服务端口
redis.timeout=3000      	 #超时时间:单位ms
redis.password=nick123    	 #授权密码

redis.pool.maxActive=200  #最大连接数:能够同时建立的“最大链接个数”

redis.pool.maxIdle=20     #最大空闲数:空闲链接数大于maxIdle时,将进行回收

redis.pool.minIdle=5      #最小空闲数:低于minIdle时,将创建新的链接

redis.pool.maxWait=3000    #最大等待时间:单位ms

redis.pool.testOnBorrow=true   #使用连接时,检测连接是否成功 
  redis.pool.testOnReturn=true  #返回连接时,检测连接是否成功

3. 加载属性文件:redis.properties

ResourceBundle bundle = ResourceBundle.getBundle("redis");

4. 创建配置对象:

JedisPoolConfig config = new JedisPoolConfig();
String host = bundle.getString("redis.host");
...
config.setMaxActive(Integer.valueOf(bundle.getString("redis.pool.maxActive")));
...
config.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow")));
...

5. 创建Jedis连接池:

JedisPool pool = new JedisPool(config, host, port, timeout, password);

[三]. 使用方式:    
 1. 从连接池获取Jedis对象:

Jedis jedis = pool.getResource();

2. 基本操作:

jedis.set("province", "shannxi");
String province = jedis.get("province");
jedis.del("province");

3. 将Jedis对象归还给连接池:

pool.returnResource(jedis);
三、jedis与spring整合[一]. 搭建环境: 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
 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>

XML

[二]. 从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);

JAVA

[三]. 缓存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);

/**
 * 功能简述: 序列化工具类,负责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;
    }
}

JAVA代码

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[]字节数组。

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);  

请参考:http://hello-nick-xu.iteye.com/blog/2077090

时间: 2024-08-28 16:06:26

jedis入门一的相关文章

Jedis入门

一:介绍 1.Jedis的官网 2.使用 这个可以从上面的连接进入github. https://github.com/xetorthio/jedis 3.使用方式 或者使用jar包,不过这里我使用官网推荐的maven管理方式. 二:验证是否可以连接主机 1.cmd下 telnet 192.168.140.121 6379 2. 三:验证项目 1.pom文件 1 <?xml version="1.0" encoding="UTF-8"?> 2 <p

jedis入门教程

1 jedis介绍 2 java连接Redis 1 导入jar包 2 连接实例 @Test //获得单一的jedis对象操作数据库 public void test1(){ //1.获得连接对象 设置ip地址和端口 Jedis jedis = new Jedis("192.168.204.128", 6379); //2 .设置数据 jedis.set("name", "zhangsan"); //3 获得数据 String name = jed

Mac上的redis安装与jedis入门

Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件 安装与配置 (1) https://redis.io/download下载redis stable最新版 将压缩包解压到你的文件夹下 (2) 进入到redis文件夹的根目录 # 编译测试(跳过也可以)sudo make test# 编译安装sudo make install# 安装完成以后启动redis-server (3) 简单测试 新建一个terminal, 输入 redis-cli # 客

Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式)

Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式) 原文地址:http://alanland.iteye.com/admin/blogs/1600685(欢迎转载 - 转载请保留该原文链接) 07/19/12 03:08:05 PM 在Jedis开发中,我们很多时候希望直接把一个对象放到Redis中,然后在需要的时候取出来.Redis的key和value都支持二进制安全的字符串,存储Java对象不是问题,下面我们看一下如何来实现. 1要存储的对象 现在写一个

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

Redis入门很简单之七[使用Jedis实现客户端Sharding] 博客分类: NoSQL/Redis/MongoDB redisjedisspringsharding分片 <一>. 背景介绍: 1. sharding机制:即通常所说的"分片",允许数据存放在不同的物理机器上,  以适应数据量过大的场景,克服单台机器内存或者磁盘空间的限制.而这种"离散式"地存放,对客户端来说是透明的,对客户端来讲,完全看不到这种差别. 2. 常见的内存缓存中间件,比如

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

Redis入门很简单之四[初识Jedis] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存jedis 使用Jedis提供的Java API对Redis进行操作,是Redis官方推崇的方式:并且,使用Jedis提供的对Redis的支持也最为灵活.全面:不足之处,就是编码复杂度较高. [一]. 入门使用: 下载Jedis的依赖包jedis-2.1.0.jar,然后将其添加到classpath下面.然后,即可进行编程:  1. 定义连接:Redis暂时不要设置登录密码 J

Redis入门很简单之五【Jedis和Spring的整合】

Redis入门很简单之五[Jedis和Spring的整合] 博客分类: NoSQL/Redis/MongoDB redisnosql缓存jedisspring 在上一篇文章中,简单介绍了Jedis的连接池使用方式. 如果和Spring进行整合的话,我们将获得更好的简洁性.灵活性,显然是一种更加优雅(graceful)的方式. [一]. 搭建环境: 1. 在之前版本的基础之上,添加如下的依赖:   spring.jar   commons-logging.jar   log4j-1.2.15.ja

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

Redis入门很简单之六[Jedis常见操作] 博客分类: NoSQL/Redis/MongoDB redisjedisnosql缓存教程 之前介绍了Jedis的基本操作,连接池的支持,以及和Spring的整合.接下来的内容,继续Jedis的最为常见的操作.主要包括常用的列表(list).集合(set).有序集合(sorted set).哈希表(hash)等数据结构,以及其他特性支持. <一>. 使用list: 可以使用列表模拟队列(queue).堆栈(stack),并且支持双向的操作(L或者

Redis入门(九)——Jedis的基本使用

Redis入门(九)——Jedis的基本使用 目录 Jedis简介与安装 Jedis的常用API Jedis事物 Jedis连接池 1.Jedis简介与安装 Jedis简介: Jedis Client是Redis官网推荐的一个面向java客户端,库文件实现了对redis各类API进行封装调用. Jedis的安装:Java操作Redis之前,首先需要确保已经安装了 redis 服务及 Java redis 驱动.并开启redis服务. 然后新建一个maven工程,在pom文件中添加对Jedis的依