最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java利用Redis實(shí)現(xiàn)消息隊(duì)列的示例代碼

 更新時(shí)間:2017年07月24日 09:49:13   作者:遇事冷靜,臉小三分  
本篇文章主要介紹了Java利用Redis實(shí)現(xiàn)消息隊(duì)列的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

本文介紹了Java利用Redis實(shí)現(xiàn)消息隊(duì)列的示例代碼,分享給大家,具體如下:

應(yīng)用場景

為什么要用redis?

二進(jìn)制存儲(chǔ)、java序列化傳輸、IO連接數(shù)高、連接頻繁

一、序列化

這里編寫了一個(gè)java序列化的工具,主要是將對(duì)象轉(zhuǎn)化為byte數(shù)組,和根據(jù)byte數(shù)組反序列化成java對(duì)象; 主要是用到了ByteArrayOutputStream和ByteArrayInputStream; 注意:每個(gè)需要序列化的對(duì)象都要實(shí)現(xiàn)Serializable接口;

其代碼如下:

package Utils;
import java.io.*;
/**
 * Created by Kinglf on 2016/10/17.
 */
public class ObjectUtil {
 /**
  * 對(duì)象轉(zhuǎn)byte[]
  * @param obj
  * @return
  * @throws IOException
  */
 public static byte[] object2Bytes(Object obj) throws IOException{
  ByteArrayOutputStream bo=new ByteArrayOutputStream();
  ObjectOutputStream oo=new ObjectOutputStream(bo);
  oo.writeObject(obj);
  byte[] bytes=bo.toByteArray();
  bo.close();
  oo.close();
  return bytes;
 }
 /**
  * byte[]轉(zhuǎn)對(duì)象
  * @param bytes
  * @return
  * @throws Exception
  */
 public static Object bytes2Object(byte[] bytes) throws Exception{
  ByteArrayInputStream in=new ByteArrayInputStream(bytes);
  ObjectInputStream sIn=new ObjectInputStream(in);
  return sIn.readObject();
 }
}

二、消息類(實(shí)現(xiàn)Serializable接口)

package Model;

import java.io.Serializable;

/**
 * Created by Kinglf on 2016/10/17.
 */
public class Message implements Serializable {

 private static final long serialVersionUID = -389326121047047723L;
 private int id;
 private String content;
 public Message(int id, String content) {
  this.id = id;
  this.content = 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做隊(duì)列,我們采用的是redis中l(wèi)ist的push和pop操作;

結(jié)合隊(duì)列的特點(diǎn):

只允許在一端插入新元素只能在隊(duì)列的尾部FIFO:先進(jìn)先出原則 Redis中l(wèi)push頭入(rpop尾出)或rpush尾入(lpop頭出)可以滿足要求,而Redis中l(wèi)ist藥push或 pop的對(duì)象僅需要轉(zhuǎn)換成byte[]即可

java采用Jedis進(jìn)行Redis的存儲(chǔ)和Redis的連接池設(shè)置

上代碼:

package Utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * Created by Kinglf on 2016/10/17.
 */
public class JedisUtil {
 private static String JEDIS_IP;
 private static int JEDIS_PORT;
 private static String JEDIS_PASSWORD;
 private static JedisPool jedisPool;
 static {
  //Configuration自行寫的配置文件解析類,繼承自Properties
  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);
  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);
 }
 /**
  * 獲取數(shù)據(jù)
  * @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){
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();
  }finally {
   close(jedis);
  }
  return value;
 }

 private static void close(Jedis jedis) {
  try{
   jedisPool.returnResource(jedis);
  }catch (Exception e){
   if(jedis.isConnected()){
    jedis.quit();
    jedis.disconnect();
   }
  }
 }
 public static byte[] get(byte[] key){
  byte[] value = null;
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   value = jedis.get(key);
  } catch (Exception e) {
   //釋放redis對(duì)象
   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對(duì)象
   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對(duì)象
   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對(duì)象
   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對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();
  } finally {
   //返還到連接池
   close(jedis);
  }
 }

 /**
  * 獲取數(shù)據(jù)
  *
  * @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對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();
  } finally {
   //返還到連接池
   close(jedis);
  }

  return value;
 }
 /**
  * 獲取數(shù)據(jù)
  *
  * @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對(duì)象
   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對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();
  } finally {
   //返還到連接池
   close(jedis);
  }
 }
 /**
  * 存儲(chǔ)REDIS隊(duì)列 順序存儲(chǔ)
  * @param key reids鍵名
  * @param value 鍵值
  */
 public static void lpush(byte[] key, byte[] value) {

  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   jedis.lpush(key, value);
  } catch (Exception e) {
   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();
  } finally {
   //返還到連接池
   close(jedis);
  }
 }

 /**
  * 存儲(chǔ)REDIS隊(duì)列 反向存儲(chǔ)
  * @param key reids鍵名
  * @param value 鍵值
  */
 public static void rpush(byte[] key, byte[] value) {

  Jedis jedis = null;
  try {

   jedis = jedisPool.getResource();
   jedis.rpush(key, value);

  } catch (Exception e) {

   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {

   //返還到連接池
   close(jedis);

  }
 }

 /**
  * 將列表 source 中的最后一個(gè)元素(尾元素)彈出,并返回給客戶端
  * @param key reids鍵名
  * @param destination 鍵值
  */
 public static void rpoplpush(byte[] key, byte[] destination) {

  Jedis jedis = null;
  try {

   jedis = jedisPool.getResource();
   jedis.rpoplpush(key, destination);

  } catch (Exception e) {

   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {

   //返還到連接池
   close(jedis);

  }
 }

 /**
  * 獲取隊(duì)列數(shù)據(jù)
  * @param key 鍵名
  * @return
  */
 public static List lpopList(byte[] key) {

  List list = null;
  Jedis jedis = null;
  try {

   jedis = jedisPool.getResource();
   list = jedis.lrange(key, 0, -1);

  } catch (Exception e) {

   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {

   //返還到連接池
   close(jedis);

  }
  return list;
 }
 /**
  * 獲取隊(duì)列數(shù)據(jù)
  * @param 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對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {

   //返還到連接池
   close(jedis);

  }
  return bytes;
 }
 public static void hmset(Object key, Map hash) {
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   jedis.hmset(key.toString(), hash);
  } catch (Exception e) {
   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {
   //返還到連接池
   close(jedis);

  }
 }
 public static void hmset(Object key, Map hash, int time) {
  Jedis jedis = null;
  try {

   jedis = jedisPool.getResource();
   jedis.hmset(key.toString(), hash);
   jedis.expire(key.toString(), time);
  } catch (Exception e) {
   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {
   //返還到連接池
   close(jedis);

  }
 }
 public static List hmget(Object key, String... fields) {
  List result = null;
  Jedis jedis = null;
  try {

   jedis = jedisPool.getResource();
   result = jedis.hmget(key.toString(), fields);

  } catch (Exception e) {
   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {
   //返還到連接池
   close(jedis);

  }
  return result;
 }

 public static Set hkeys(String key) {
  Set result = null;
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   result = jedis.hkeys(key);

  } catch (Exception e) {
   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {
   //返還到連接池
   close(jedis);

  }
  return result;
 }
 public static List lrange(byte[] key, int from, int to) {
  List result = null;
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   result = jedis.lrange(key, from, to);

  } catch (Exception e) {
   //釋放redis對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();

  } finally {
   //返還到連接池
   close(jedis);

  }
  return result;
 }
 public static Map hgetAll(byte[] key) {
  Map result = null;
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   result = jedis.hgetAll(key);
  } catch (Exception e) {
   //釋放redis對(duì)象
   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對(duì)象
   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對(duì)象
   jedisPool.returnBrokenResource(jedis);
   e.printStackTrace();
  } finally {
   //返還到連接池
   close(jedis);
  }
  return len;
 }
}

四、Configuration主要用于讀取Redis的配置信息

package Utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by Kinglf on 2016/10/17.
 */
public class Configuration extends Properties {

 private static final long serialVersionUID = -2296275030489943706L;
 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 ioe) {

  }
 }
}

五、測試

import Model.Message;
import Utils.JedisUtil;
import Utils.ObjectUtil;
import redis.clients.jedis.Jedis;

import java.io.IOException;

/**
 * Created by Kinglf on 2016/10/17.
 */
public class TestRedisQueue {
 public static byte[] redisKey = "key".getBytes();
 static {
  try {
   init();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 private static void init() throws IOException {
  for (int i = 0; i < 1000000; i++) {
   Message message = new Message(i, "這是第" + i + "個(gè)內(nèi)容");
   JedisUtil.lpush(redisKey, ObjectUtil.object2Bytes(message));
  }

 }

 public static void main(String[] args) {
  try {
   pop();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 private static void pop() throws Exception {
  byte[] bytes = JedisUtil.rpop(redisKey);
  Message msg = (Message) ObjectUtil.bytes2Object(bytes);
  if (msg != null) {
   System.out.println(msg.getId() + "----" + msg.getContent());
  }
 }
}

每執(zhí)行一次pop()方法,結(jié)果如下:
<br>1----這是第1個(gè)內(nèi)容
<br>2----這是第2個(gè)內(nèi)容
<br>3----這是第3個(gè)內(nèi)容
<br>4----這是第4個(gè)內(nèi)容

總結(jié)

至此,整個(gè)Redis消息隊(duì)列的生產(chǎn)者和消費(fèi)者代碼已經(jīng)完成

1.Message 需要傳送的實(shí)體類(需實(shí)現(xiàn)Serializable接口)

2.Configuration Redis的配置讀取類,繼承自Properties

3.ObjectUtil 將對(duì)象和byte數(shù)組雙向轉(zhuǎn)換的工具類

4.Jedis 通過消息隊(duì)列的先進(jìn)先出(FIFO)的特點(diǎn)結(jié)合Redis的list中的push和pop操作進(jìn)行封裝的工具類

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • redis與spring整合使用的步驟實(shí)例教程

    redis與spring整合使用的步驟實(shí)例教程

    這篇文章主要給大家介紹了關(guān)于redis與spring整合使用的相關(guān)資料,文中通過示例代碼將實(shí)現(xiàn)的步驟一步步介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2018-03-03
  • springboot hazelcast緩存中間件的實(shí)例代碼

    springboot hazelcast緩存中間件的實(shí)例代碼

    這篇文章主要介紹了springboot hazelcast緩存中間件的實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-08-08
  • Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之生活旅行分享平臺(tái)的實(shí)現(xiàn)

    Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之生活旅行分享平臺(tái)的實(shí)現(xiàn)

    這是一個(gè)使用了java+Springboot+JPA+Jsp+Html+js+Ajax+maven+mysql開發(fā)的生活旅行分享平臺(tái),是一個(gè)畢業(yè)設(shè)計(jì)的實(shí)戰(zhàn)練習(xí),具有分享發(fā)布平臺(tái)該有的所有功能,感興趣的朋友快來看看吧
    2022-02-02
  • 新版Android?Studio修改jdk版本的簡單步驟

    新版Android?Studio修改jdk版本的簡單步驟

    這篇文章主要介紹了新版Android?Studio修改jdk版本的簡單步驟,升級(jí)Android?Studio后,JDK版本設(shè)置選項(xiàng)消失,可以通過Settings面板進(jìn)入Gradle設(shè)置,修改GradleJDK路徑來解決問題,需要的朋友可以參考下
    2025-03-03
  • java中如何對(duì)arrayList按數(shù)字大小逆序排序

    java中如何對(duì)arrayList按數(shù)字大小逆序排序

    這篇文章主要介紹了java中如何對(duì)arrayList按數(shù)字大小逆序排序問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java HTTP協(xié)議收發(fā)MQ 消息代碼實(shí)例詳解

    Java HTTP協(xié)議收發(fā)MQ 消息代碼實(shí)例詳解

    這篇文章主要通過實(shí)例代碼為大家詳細(xì)介紹了如何在Java 環(huán)境下使用 HTTP 協(xié)議收發(fā) MQ 消息,需要的朋友可以參考下
    2017-04-04
  • Springboot實(shí)現(xiàn)Activemq死信隊(duì)列詳解

    Springboot實(shí)現(xiàn)Activemq死信隊(duì)列詳解

    這篇文章主要介紹了Springboot實(shí)現(xiàn)Activemq死信隊(duì)列詳解,Activemq服務(wù)端配置重新投遞次數(shù)超過?MaximumRedeliveries?,則會(huì)進(jìn)入死信隊(duì)列,默認(rèn)情況,有一個(gè)死信隊(duì)列:AcitveMQ.DLQ,所有的消息都投遞到此隊(duì)列,包括過期消息,重投遞失敗消息,需要的朋友可以參考下
    2023-12-12
  • 關(guān)于服務(wù)網(wǎng)關(guān)Spring Cloud Zuul(Finchley版本)

    關(guān)于服務(wù)網(wǎng)關(guān)Spring Cloud Zuul(Finchley版本)

    這篇文章主要介紹了關(guān)于服務(wù)網(wǎng)關(guān)Spring Cloud Zuul(Finchley版本),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java Swing實(shí)現(xiàn)坦克大戰(zhàn)游戲

    Java Swing實(shí)現(xiàn)坦克大戰(zhàn)游戲

    這篇文章主要介紹了Java Swing實(shí)現(xiàn)坦克大戰(zhàn)游戲,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有很大的幫助喲,需要的朋友可以參考下
    2021-05-05
  • Spring?Data?JPA?映射VO/DTO對(duì)象方式

    Spring?Data?JPA?映射VO/DTO對(duì)象方式

    這篇文章主要介紹了Spring?Data?JPA?映射VO/DTO對(duì)象方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11

最新評(píng)論

楚雄市| 阳朔县| 镇宁| 新余市| 恩平市| 贡觉县| 丹凤县| 曲麻莱县| 北安市| 赤壁市| 汝南县| 广元市| 枣阳市| 攀枝花市| 凤翔县| 丹巴县| 乡城县| 宜昌市| 公安县| 郑州市| 屏南县| 磐石市| 博野县| 视频| 清水县| 兰州市| 监利县| 兴隆县| 宽城| 沐川县| 杭锦旗| 眉山市| 山西省| 河源市| 繁峙县| 南宁市| 丰宁| 浦城县| 秦安县| 呼和浩特市| 乐安县|