`

java redis使用之利用jedis实现redis消息队列

阅读更多

序列化工具类:

 

package com.bean.util;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectUtil {
    /**对象转byte[]
     * @param obj
     * @return
     * @throws IOException
     */
    public static byte[] objectToBytes(Object obj) throws Exception{
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        byte[] bytes = bo.toByteArray();
        bo.close();
        oo.close();
        return bytes;
    }
    /**byte[]转对象
     * @param bytes
     * @return
     * @throws Exception
     */
    public static Object bytesToObject(byte[] bytes) throws Exception{
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream sIn = new ObjectInputStream(in);
        return sIn.readObject();
    }
}

 消息类,主要用于接收消息内容和消息下表的设置:

 

 

package com.bean;
 
import java.io.Serializable;
 
/**定义消息类接收消息内容和设置消息的下标
 * @author lenovo
 *
 */
public class Message implements Serializable{
    private static final long serialVersionUID = 7792729L;
    private int id;
    private String content;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

 利用redis做队列,我们采用的是redis中list的push和pop操作;

 

结合队列的特点:

只允许在一端插入新元素只能在队列的尾部FIFO:先进先出原则

redis中lpush(rpop)或rpush(lpop)可以满足要求,而redis中list 里要push或pop的对象仅需要转换成byte[]即可

java采用Jedis进行redis的存储和redis的连接池设置

 

package com.redis.util;
 
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
 
public class JedisUtil {
 
    private static String JEDIS_IP;
    private static int JEDIS_PORT;
    private static String JEDIS_PASSWORD;
    //private static String JEDIS_SLAVE;
 
    private static JedisPool jedisPool;
 
    static {
        Configuration conf = Configuration.getInstance();
        JEDIS_IP = conf.getString("jedis.ip", "127.0.0.1");
        JEDIS_PORT = conf.getInt("jedis.port", 6379);
        JEDIS_PASSWORD = conf.getString("jedis.password", null);
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxActive(5000);
        config.setMaxIdle(256);//20
        config.setMaxWait(5000L);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        config.setMinEvictableIdleTimeMillis(60000l);
        config.setTimeBetweenEvictionRunsMillis(3000l);
        config.setNumTestsPerEvictionRun(-1);
        jedisPool = new JedisPool(config, JEDIS_IP, JEDIS_PORT, 60000);
    }
 
    /**
     * 获取数据
     * @param key
     * @return
     */
    public static String get(String key) {
 
        String value = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
 
        return value;
    }
 
    public static void close(Jedis jedis) {
        try {
            jedisPool.returnResource(jedis);
 
        } catch (Exception e) {
            if (jedis.isConnected()) {
                jedis.quit();
                jedis.disconnect();
            }
        }
    }
 
    /**
     * 获取数据
     * 
     * @param key
     * @return
     */
    public static byte[] get(byte[] key) {
 
        byte[] value = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
 
        return value;
    }
 
    public static void set(byte[] key, byte[] value) {
 
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
    }
 
    public static void set(byte[] key, byte[] value, int time) {
 
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
            jedis.expire(key, time);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
    }
 
    public static void hset(byte[] key, byte[] field, byte[] value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.hset(key, field, value);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
    }
 
    public static void hset(String key, String field, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.hset(key, field, value);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
    }
 
    /**
     * 获取数据
     * 
     * @param key
     * @return
     */
    public static String hget(String key, String field) {
 
        String value = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.hget(key, field);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
 
        return value;
    }
 
    /**
     * 获取数据
     * 
     * @param key
     * @return
     */
    public static byte[] hget(byte[] key, byte[] field) {
 
        byte[] value = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.hget(key, field);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
 
        return value;
    }
 
    public static void hdel(byte[] key, byte[] field) {
 
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.hdel(key, field);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
    }
 
    /**
     * 存储REDIS队列 顺序存储
     * @param byte[] key reids键名
     * @param byte[] value 键值
     */
    public static void lpush(byte[] key, byte[] value) {
 
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            jedis.lpush(key, value);
 
        } catch (Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
 
            //返还到连接池
            close(jedis);
 
        }
    }
 
    /**
     * 存储REDIS队列 反向存储
     * @param byte[] key reids键名
     * @param byte[] value 键值
     */
    public static void rpush(byte[] key, byte[] value) {
 
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            jedis.rpush(key, value);
 
        } catch (Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
 
            //返还到连接池
            close(jedis);
 
        }
    }
 
    /**
     * 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端
     * @param byte[] key reids键名
     * @param byte[] value 键值
     */
    public static void rpoplpush(byte[] key, byte[] destination) {
 
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            jedis.rpoplpush(key, destination);
 
        } catch (Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
 
            //返还到连接池
            close(jedis);
 
        }
    }
 
    /**
     * 获取队列数据
     * @param byte[] key 键名
     * @return
     */
    public static List<byte[]> lpopList(byte[] key) {
 
        List<byte[]> list = null;
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            list = jedis.lrange(key, 0, -1);
 
        } catch (Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
 
            //返还到连接池
            close(jedis);
 
        }
        return list;
    }
 
    /**
     * 获取队列数据
     * @param byte[] key 键名
     * @return
     */
    public static byte[] rpop(byte[] key) {
 
        byte[] bytes = null;
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            bytes = jedis.rpop(key);
 
        } catch (Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
 
            //返还到连接池
            close(jedis);
 
        }
        return bytes;
    }
 
    public static void hmset(Object key, Map<string, string=""> hash) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.hmset(key.toString(), hash);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
            //返还到连接池
            close(jedis);
 
        }
    }
 
    public static void hmset(Object key, Map<string, string=""> hash, int time) {
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            jedis.hmset(key.toString(), hash);
            jedis.expire(key.toString(), time);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
            //返还到连接池
            close(jedis);
 
        }
    }
 
    public static List<string> hmget(Object key, String... fields) {
        List<string> result = null;
        Jedis jedis = null;
        try {
 
            jedis = jedisPool.getResource();
            result = jedis.hmget(key.toString(), fields);
 
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
            //返还到连接池
            close(jedis);
 
        }
        return result;
    }
 
    public static Set<string> hkeys(String key) {
        Set<string> result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.hkeys(key);
 
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
            //返还到连接池
            close(jedis);
 
        }
        return result;
    }
 
    public static List<byte[]> lrange(byte[] key, int from, int to) {
        List<byte[]> result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.lrange(key, from, to);
 
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
            //返还到连接池
            close(jedis);
 
        }
        return result;
    }
 
    public static Map<byte[],> hgetAll(byte[] key) {
        Map<byte[],> result = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.hgetAll(key);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        } finally {
            //返还到连接池
            close(jedis);
        }
        return result;
    }
 
    public static void del(byte[] key) {
 
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
    }
 
    public static long llen(byte[] key) {
 
        long len = 0;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.llen(key);
        } catch (Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            //返还到连接池
            close(jedis);
        }
        return len;
    }
 
}

 Configuration主要用于读取redis配置信息

 

package com.redis.util;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class Configuration extends Properties {
 
    private static final long serialVersionUID = 50440463580273222L;
 
    private static Configuration instance = null;
 
    public static synchronized Configuration getInstance() {
        if (instance == null) {
            instance = new Configuration();
        }
        return instance;
    }
 
    public String getProperty(String key, String defaultValue) {
        String val = getProperty(key);
        return (val == null || val.isEmpty()) ? defaultValue : val;
    }
 
    public String getString(String name, String defaultValue) {
        return this.getProperty(name, defaultValue);
    }
 
    public int getInt(String name, int defaultValue) {
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    }
 
    public long getLong(String name, long defaultValue) {
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    }
 
    public float getFloat(String name, float defaultValue) {
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Float.parseFloat(val);
    }
 
    public double getDouble(String name, double defaultValue) {
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Double.parseDouble(val);
    }
 
    public byte getByte(String name, byte defaultValue) {
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Byte.parseByte(val);
    }
 
    public Configuration() {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("config.xml");
        try {
            this.loadFromXML(in);
            in.close();
        } catch (IOException e) {
        }
    }
}

 测试redis队列

package com.quene.test;
 
import com.bean.Message;
import com.bean.util.ObjectUtil;
import com.redis.util.JedisUtil;
 
public class TestRedisQuene {
    public static byte[] redisKey = "key".getBytes();
    static{
        init();
    }
    public static void main(String[] args) {
        pop();
    }
 
    private static void pop() {
        byte[] bytes = JedisUtil.rpop(redisKey);
        Message msg = (Message) ObjectUtil.bytesToObject(bytes);
        if(msg != null){
            System.out.println(msg.getId()+"   "+msg.getContent());
        }
    }
 
    private static void init() {
        Message msg1 = new Message(1, "内容1");
        JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg1));
        Message msg2 = new Message(2, "内容2");
        JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg2));
        Message msg3 = new Message(3, "内容3");
        JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg3));
    }
 
}

 

分享到:
评论
3 楼 lijunxian0114 2017-06-06  
<?xml version="1.0" encoding="UTF-8"?>
<redis>
    <id>127.0.0.1</id>
    <port>6379</port>
    <password></password>
</redis>
2 楼 feiteyizu 2017-05-11  
YbhLzz 写道
你好,请问下config.xml 能提供下载吗?

哪有config.xml?
1 楼 YbhLzz 2017-05-05  
你好,请问下config.xml 能提供下载吗?

相关推荐

    java redis使用之利用jedis实现redis消息队列.docx

    ### Java Redis 使用之利用 Jedis 实现 Redis 消息队列 #### 一、引言 随着互联网应用的发展,消息队列在系统架构中的地位愈发重要。它不仅可以提高系统的响应速度,还可以帮助开发者构建出更加健壮、可扩展的应用...

    各种版本的redis+Jedis驱动包

    Redis是一种开源的、基于键值对的数据存储系统,常用于数据缓存、消息队列以及数据库功能。它以其高性能、高可用性和丰富的数据结构而受到广大开发者喜爱。在这个压缩包中,包含了不同平台下的Redis安装包,以及...

    Java利用Redis实现消息队列的示例代码

    Java利用Redis实现消息队列的示例代码 以下是Java利用Redis实现消息队列的示例代码的知识点总结: 一、序列化 * 序列化是将对象转换为byte数组的过程,Java中可以使用ByteArrayOutputStream和...

    Java实现Redis的消息订阅和发布

    标签"redis队列"提示我们,Redis不仅仅可以作为发布/订阅系统,还可以用于构建消息队列,例如使用`RPOPLPUSH`或`BLPOP`命令实现先进先出(FIFO)队列。然而,对于大型高并发系统,可能需要考虑使用Redis的Stream或更...

    redis安装脚本+jedis.jar.zip

    Redis是一款高性能的键值数据库,常用于数据缓存、消息队列等场景。Jedis是Java语言连接Redis的客户端库,提供了丰富的API供开发者进行数据操作。本文将详细介绍如何使用提供的"redis安装脚本+jedis.jar.zip"进行...

    Redis使用lettuce和jedis.pdf

    在Java应用程序中,常用的操作Redis的方式有使用Jedis和Lettuce这两个客户端。 Jedis是一个简单的Redis客户端,它以单线程方式与Redis服务器进行交互,支持连接池管理。Lettuce是另一个Redis客户端,它基于Netty...

    redis辅助文档 + jedis

    - **消息队列**: 利用`RPUSH`和`BLPOP`实现阻塞式消息队列,处理异步任务。 - **计数器**: 对指定键进行原子递增或递减操作,统计访问次数等。 - **分布式锁**: 使用`SETNX`或`乐观锁`实现分布式锁,保证多节点间...

    Redis使用lettuce和jedis

    Redis是一款高性能的键值对数据存储系统,常用于缓存、消息队列和数据库功能。在Java中,我们可以使用Lettuce和Jedis这两个客户端库与Redis进行交互。本篇文章将详细探讨这两种客户端的使用方法及其特点。 首先,...

    (window)Redis安装包,Redis桌面Manager,Jedis驱动包

    Redis是一款开源的、高性能的键值对存储系统,常用于数据缓存、消息队列以及数据库功能。在Windows操作系统上安装Redis,可以显著提升应用程序的数据处理速度。本压缩包提供了在Windows环境下安装和管理Redis所需的...

    jedis-2.9.0 最新版Redis客户端CSDN下载

    Jedis是Java语言中使用最广泛的Redis客户端库,它提供了丰富的API来操作Redis服务器。在这个"jedis-2.9.0"的最新版本中,我们包含了三个重要的文件: 1. `jedis-2.9.0.jar`:这是Jedis的二进制发行版,包含了所有...

    jedis(java连接redis)

    2. **发布订阅**:通过Jedis实现消息的发布和订阅功能。 ```java JedisPubSub pubSub = new MyPubSubListener(); jedis.psubscribe(pubSub, "pattern*"); ``` 3. **脚本操作**:使用Lua脚本在服务器端执行复杂...

    java连接redis/jedis连接池/jedis相关工具/jedis对象存取

    Java连接Redis是现代Web开发中常见的一种数据存储和交互方式,Redis作为一个高性能的键值数据库,因其快速响应和丰富的数据结构支持,常被用于缓存、消息队列等场景。Jedis是Java语言中广泛使用的Redis客户端库,它...

    redis常用命令,redis配置文件,redis持久化,redis事务,redis主从复制,jedis的使用

    Redis 是一种开源、基于内存的数据结构存储系统,可以用作数据库、消息队列、缓存层等。下面是对 Redis 的常用命令、配置文件、持久化、事务、主从复制、Jedis 使用的详细讲解。 Redis 常用命令 Redis 提供了很多...

    java redis 各类型操作实例

    在Java开发中,Redis是一个非常流行的高性能键值存储系统,常用于缓存、消息队列等场景。本文将深入探讨如何使用Java与Redis进行各种类型的操作,并基于Maven项目管理来构建我们的示例代码。 首先,为了在Java项目...

    java redis 发布与订阅小demo jedis

    在Java编程中,Redis是一个非常流行的开源键值存储系统,常用于数据缓存、消息队列等场景。Redis提供了发布/订阅(Publish/Subscribe)功能,使得多个客户端可以订阅特定的频道,当有其他客户端向该频道发布消息时,...

    java连接redis的jedis.jar包

    Redis是一个高性能的键值数据库,常被用作缓存、消息队列等场景,而Jedis则是Java语言中对Redis服务接口进行封装的库,方便Java程序与Redis服务器进行交互。下面将详细阐述Jedis库的使用方法、核心概念以及如何在...

    redis的安装包以及jedis 的jar

    Redis 的高效性能和丰富数据结构,配合 Jedis 的便捷操作,让它们在缓存、消息队列、实时数据存储等多个领域都有广泛应用。理解并熟练掌握 Redis 的安装与配置,以及 Jedis 的使用,对于提升应用程序的性能和可靠性...

    redis的Java客户端jedis使用示例.rar

    Redis是一款高性能的键值对数据库,广泛应用于缓存、消息队列、数据持久化等多个场景。Jedis是Java社区中最常用的Redis客户端库,它提供了丰富的API来操作Redis服务器。本示例将详细介绍如何在Java应用中使用Jedis...

    redis连接池jar jedis+common

    Redis是一款高性能的键值对数据存储系统,常用于缓存、消息队列和数据库功能。在Java开发中,我们通常会使用Jedis作为与Redis进行交互的客户端库。"redis连接池jar jedis+common"指的是在Java应用中,通过Jedis连接...

    DelayQueue延迟队列和Redis缓存实现订单自动取消功能

    3. 使用Jedis或者其他Redis客户端连接到Redis服务器,将订单信息存储为键值对,键是订单号,值是订单数据,同时设置键的过期时间为订单的超时时间。 4. 开启一个后台线程或使用ScheduledExecutorService定期检查...

Global site tag (gtag.js) - Google Analytics