Redis列表List是采用的雙端鏈表的結(jié)構(gòu),所有頭尾存取元素特別快
手動(dòng)操作一下在java中實(shí)現(xiàn)redis的消息隊(duì)列柠偶,通過生產(chǎn)者和消費(fèi)者的模式進(jìn)行實(shí)現(xiàn)
生產(chǎn)者代碼:
public class Producer extends Thread{
public static final String messageKey = "message";
private JedisPool jedisPool;
private String producerName;
private Jedis jedis;
private volatile int count = 0;
public Producer(String producerName){
this.producerName = producerName;
jedisPool = new JedisPool("127.0.0.1",6379);//redis的ip和端口
jedis = jedisPool.getResource();
}
public void putMessage(String message){
jedis.lpush(messageKey,message);
count++;
}
public void run(){
while (true){
try {
putMessage(RandomStringUtils.randomAlphabetic(5));//獲取長(zhǎng)度為5的任意字符串
TimeUnit.SECONDS.sleep(1);//線程進(jìn)入為時(shí)一秒的休眠狀態(tài)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public int getCount(){
return count;
}
public static void main(String[] args) throws InterruptedException {
Producer producer = new Producer("myTest");
producer.start();
for (;;){
System.out.println("生產(chǎn)者:"+producer.producerName+"生產(chǎn)了"+producer.getCount()+"對(duì)象");
TimeUnit.SECONDS.sleep(10);
}
}
}
消費(fèi)者代碼
public class Customer extends Thread{
private String customerName;
private volatile int count = 0;
private Jedis jedis;
private JedisPool jedisPool;
public Customer(String customerName){
this.customerName = customerName;
jedisPool = new JedisPool("127.0.0.1",6379);
jedis = jedisPool.getResource();
}
//注意點(diǎn)
public void getMessage(){
List<String> result = jedis.blpop(0,Producer.messageKey);
if (result.size()!=0){
String rkey = result.get(0);
if (rkey.equals(Producer.messageKey)){
String msg = result.get(1);
count++;
showMessage(msg);
}
}
}
public void showMessage(String msg){
System.out.println("消費(fèi)者:"+customerName+"消息內(nèi)容是"+msg+"這是第"+count+"個(gè)產(chǎn)品");
}
public void run(){
while (true){
getMessage();
}
}
public static void main(String[] args) {
Customer customer = new Customer("消費(fèi)一號(hào)");
customer.start();
}
}
其中比較重要的方法就是getMessage(),可以看到我使用的是blpop()的方式取出消息的次哈,因?yàn)閎lpop是一個(gè)阻塞的方法胎署,當(dāng)消息隊(duì)列中沒有元素,那么就會(huì)一直進(jìn)入到阻塞的狀態(tài)亿乳,如果使用lpop的方式硝拧,那么就會(huì)一直進(jìn)行嘗試,會(huì)浪費(fèi)很多的資源葛假,得不償失障陶,所以在此使用擁有阻塞功能的blpop()方法可以提供資源的利用率。
redis還提供了訂閱者和發(fā)布者的功能聊训,類似于QQ聊天抱究,可以私聊,群聊的方式带斑。
發(fā)布者代碼
public class Publisher {
public static final String channel = "aChannel";
private JedisPool jedisPool;
private Jedis jedis;
private String pname;
public Publisher(String pname){
this.pname = pname;
jedisPool = new JedisPool("127.0.0.1",6379);
jedis = jedisPool.getResource();
}
public void publish(String msg){
if (org.apache.commons.lang.StringUtils.isBlank(msg))
return;
jedis.publish(channel,msg);
}
public static void main(String[] args) {
Publisher publisher = new Publisher("發(fā)布者");
publisher.publish("cececcee");
}
}
這個(gè)代碼塊主要注意在方法publish中鼓寺,發(fā)布消息的時(shí)候,消息不能為空勋磕,如果傳入空值字符串則直接返回妈候。
訂閱者
public class Subscriber {
private final String exitInfo = "exit";
private JedisPool jedisPool;
private Jedis jedis;
private String subscriber;
public Subscriber(String subscriber){
this.subscriber = subscriber;
jedisPool = new JedisPool("127.0.0.1",6379);
jedis = jedisPool.getResource();
}
public void subscribe(String ...channel){
if (channel==null || channel.length<=0)
return;
JedisPubSub jedisPubSub = new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
if (Publisher.channel.equals(channel)){
System.out.println("接收到頻道:"+channel+"的消息:"+message);
if (message.equals(exitInfo)){
System.exit(0);
}
}
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
if (Publisher.channel.equals(channel)){
System.out.println("訂閱了頻道:"+channel);
}
}
};
jedis.subscribe(jedisPubSub,channel);
}
public static void main(String[] args) {
Subscriber subscriber = new Subscriber("訂閱者");
subscriber.subscribe(Publisher.channel);
}
}
訂閱者中,主要注意JedisPubSub這個(gè)類挂滓,JedisPubSub類是一個(gè)沒有抽象方法的抽象類,里面方法都是一些空實(shí)現(xiàn)苦银,所以我們可以選擇性的去重寫某些方法來實(shí)現(xiàn)我們的目的,在代碼塊中可以看出我重寫了onMessage()方法和onSubscribe()方法,前一個(gè)方法是在接收數(shù)據(jù)時(shí)候的處理幔虏,后一個(gè)方法是在訂閱頻道時(shí)候的處理纺念,最后再調(diào)用jedis的subscribe()方法來實(shí)現(xiàn)訂閱頻道。
經(jīng)過測(cè)試想括,成功發(fā)送和接收信息陷谱。
總結(jié)
使用Redis的List數(shù)據(jù)結(jié)構(gòu)可以簡(jiǎn)單迅速地做一個(gè)消息隊(duì)列,同時(shí)Redis提供的BRPOP和BLPOP等指令解決了頻繁調(diào)用Jedis的rpop和lpop方法造成的資源浪費(fèi)問題瑟蜈。除此之外烟逊,Redis提供對(duì)發(fā)布/訂閱模式的指令,可以實(shí)現(xiàn)消息傳遞踪栋、進(jìn)程間通信焙格。
補(bǔ)充說明隨機(jī)字符串實(shí)現(xiàn)類
//產(chǎn)生5位長(zhǎng)度的隨機(jī)字符串,中文環(huán)境下是亂碼
RandomStringUtils.random(5);
//使用指定的字符生成5位長(zhǎng)度的隨機(jī)字符串
RandomStringUtils.random(5, new char[]{'a','b','c','d','e','f', '1', '2', '3'});
//生成指定長(zhǎng)度的字母和數(shù)字的隨機(jī)組合字符串
RandomStringUtils.randomAlphanumeric(5);
//生成隨機(jī)數(shù)字字符串
RandomStringUtils.randomNumeric(5);
//生成隨機(jī)[a-z]字符串夷都,包含大小寫
RandomStringUtils.randomAlphabetic(5);
//生成從ASCII 32到126組成的隨機(jī)字符串
RandomStringUtils.randomAscii(4)
想要使用這個(gè)類的方法需要導(dǎo)入相應(yīng)的包
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.lang</artifactId>
<version>2.6</version>
</dependency>
參考鏈接:https://blog.csdn.net/qq_34212276/article/details/78455004