package cn.cicoding.utils;

import org.json.JSONException;
import org.json.JSONObject; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisConnectionException; class MQClient {
public static final int MSG_REALTIME = 1;
public static final int MSG_CACHED = 2;
public static final int MSG_SERIALIZABLE = 3;
public static final String NOTIFY_CHANNEL = "ClientNotify"; private JedisPool pool;
private boolean exit;
private JedisPubSub pubsub; public MQClient(String ip, int port, JedisPubSub pubsub) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxWaitMillis(10 * 1000);
config.setMaxIdle(1000);
config.setTestOnBorrow(true);
pool = new JedisPool(config, ip, port, Protocol.DEFAULT_TIMEOUT, null);
exit = false;
this.pubsub = pubsub;
} public boolean publish(String channels, String message, String content) {
JSONObject obj = new JSONObject();
boolean ret = false;
Jedis jedis = null;
try {
jedis = pool.getResource();
if (message != null) {
obj.put("message", message);
}
try {
JSONObject objCon = new JSONObject(content);
obj.put("content", objCon);
} catch (JSONException e) {
obj.put("content", content);
}
String[] tmp = channels.split(";");
for (String channel : tmp) {
try {
if (jedis.publish(channel, obj.toString()) > 0) {
ret = true;
}
} catch (Exception e) {
break;
}
}
} catch (JSONException e) {
} finally {
if (jedis != null){
jedis.close();
}
} return ret;
} public boolean clientNotify(String clients, String message, String content, int type) {
if (type == MSG_REALTIME) {
return publish(clients, message, content);
} boolean ret = false; try {
JSONObject obj = new JSONObject();
obj.put("clients", clients);
obj.put("type", type);
if (message != null) {
obj.put("message", message);
}
try {
JSONObject objCon = new JSONObject(content);
obj.put("content", objCon);
} catch (JSONException e) {
obj.put("content", content);
} if (pool.getResource().publish(NOTIFY_CHANNEL, obj.toString()) > 0) {
ret = true;
}
} catch (JSONException e) {
} return ret;
} public boolean setValue(String key, String value) {
try {
String response = pool.getResource().set(key, value);
if (response != null && response.equals("OK")) {
return true;
}
} catch (JedisConnectionException e) {
e.printStackTrace();
} return false;
} public String getValue(String key) {
return pool.getResource().get(key);
} public void subscribe(String... channels) {
while (!exit) {
try {
pool.getResource().subscribe(pubsub, channels);
} catch (JedisConnectionException e) {
e.printStackTrace();
System.out.println("try reconnect");
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}

Test测试函数:

package cn.cicoding.utils;

import redis.clients.jedis.JedisPubSub;

public class Test extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
System.out.println(channel + ":" + message);
} public static void main(String[] args) {
MQClient client = new MQClient("127.0.0.1", 6379, new Test());
client.setValue("abc", "java setted");
System.out.println(client.getValue("abc"));
System.out.println(client.clientNotify("nodeSubscriber", "message from java", "{\"debug\":0}", MQClient.MSG_REALTIME));
client.subscribe("testInitiativePerception");
}
}

Redis的消息订阅/发布 Utils工具类的更多相关文章

  1. 基于Redis的消息订阅/发布

    在工业生产设计中,我们往往需要实现一个基于消息订阅的模式,用来对非定时的的消息进行监听订阅. 这种设计模式在 总线设计模式中得到体现.微软以前的WCF中实现了服务总线 ServiceBus的设计模式. ...

  2. [SpingBoot guides系列翻译]Redis的消息订阅发布

    Redis的消息 部分参考链接 原文 CountDownLatch 概述 目的 这节讲的是用Redis来实现消息的发布和订阅,这里会使用Spring Data Redis来完成. 这里会用到两个东西, ...

  3. SpringBoot+Redis 实现消息订阅发布

    什么是 Redis Redis 是一个开源的使用 ANSI C语言编写的内存数据库,它以 key-value 键值对的形式存储数据,高性能,读取速度快,也提供了持久化存储机制. Redis 通常在项目 ...

  4. redis实现消息队列&发布/订阅模式使用

    在项目中用到了redis作为缓存,再学习了ActiveMq之后想着用redis实现简单的消息队列,下面做记录.   Redis的列表类型键可以用来实现队列,并且支持阻塞式读取,可以很容易的实现一个高性 ...

  5. 基于redis的消息订阅与发布

    Redis 的 SUBSCRIBE 命令可以让客户端订阅任意数量的频道, 每当有新信息发送到被订阅的频道时, 信息就会被发送给所有订阅指定频道的客户端. 作为例子, 下图展示了频道 channel1  ...

  6. Redis之Redis消息订阅发布简介

    概念: Redis消息订阅发布是进程间的一种消息通信模式,发送者pub发送消息,订阅者sub接收消息. 使用须知: 需要先订阅后发布,才能接收到消息.在订阅时,相当于创建了可供发布的频道. 案例: ( ...

  7. Redis实现消息的发布/订阅

    利用spring-boot结合redis进行消息的发布与订阅: 发布: class Publish { private static String topicName = “Topic:chat”; ...

  8. Redis的消息订阅及发布及事务机制

    Redis的消息订阅及发布及事务机制 订阅发布 SUBSCRIBE PUBLISH 订阅消息队列及发布消息. # 首先要打开redis-cli shell窗口 一个用于消息发布 一个用于消息订阅 # ...

  9. spring boot: 用redis的消息订阅功能更新应用内的caffeine本地缓存(spring boot 2.3.2)

    一,为什么要更新caffeine缓存? 1,caffeine缓存的优点和缺点 生产环境中,caffeine缓存是我们在应用中使用的本地缓存, 它的优势在于存在于应用内,访问速度最快,通常都不到1ms就 ...

随机推荐

  1. 分享一个linux系统中采用嵌套for循环比较两个数组内容,并输出相同值的shell脚本

    #!/bin/bash array1=(1 3 5 6 7 9) array2=(3 4 9) echo array1=${array1[@]} echo array2=${array2[@]} fo ...

  2. centos7安装nginx并配置前端环境

    服务器环境:CentOS Linux release 7.5.1804 (Core) 安装路径:/usr/local 1.安装编译工具以及库文件 (新服务器,未安装则需要先安装) # yum -y i ...

  3. JavaScript ES6 class指南

    前言 EcmaScript 2015 (又称ES6)通过一些新的关键字,使类成为了JS中一个新的一等公民.但是目前为止,这些关于类的新关键字仅仅是建立在旧的原型系统上的语法糖,所以它们并没有带来任何的 ...

  4. java基础笔记(3)

    捕获异常: try{ ...... }catch(Exception e){ ...... }finally{ ...... } 注意:在写多重catch时需先小后大: 自定义异常: String字符 ...

  5. 【洛谷 P1879】【[USACO06NOV]玉米田Corn Fields】

    题目: 链接 思路: Q:如何想到是状压DP? A:那是因为(我看了标签)\(1 ≤ M ≤ 12; 1 ≤ N ≤ 12\),\(2 ^ {12}\) 不过才...(Win7计算器使用中)\(409 ...

  6. 小白学Python——用 百度翻译API 实现 翻译功能

    本人英语不好,很多词组不认识,只能借助工具:百度翻译和谷歌翻译都不错,近期自学Python,就想能否自己设计一个百度翻译软件呢? 百度翻译开放平台: http://api.fanyi.baidu.co ...

  7. 思维体操: HDU1008 Elevator

    Elevator Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  8. 使用SecureCRT 8.5快速打开sftp传输文件

    一般使用Windows系统上安装的SecureCRT 8.5软件远程连接Linux服务器,通常给Linux系统传输文件或者使用FTP,或者使用SFTP等其他第三方软件,有时Linux系统上还需要做其他 ...

  9. Api接口管理工具推荐

    在App开发过程中少不了跟服务端打交道,各种HTTP接口调试.返回数据处理占据了不少开发时间,一款好的接口管理工具就非常有必要了.接口管理工具一方面起到链接后台开发人员和App开发人员的作用,另一方面 ...

  10. ELK7.X中配置x-pack

    ELK7.X中配置x-pack 1.X-Pack简介 X-Pack是一个Elastic Stack的扩展,将安全,警报,监视,报告和图形功能包含在一个易于安装的软件包中.虽然elasticsearch ...