1. Server
package com.dz.im.tools;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* message publisher
* @author David
*
*/
public class PubClient {
// Redis server IP
private static String ADDR = "192.168.0.11";
// Redis port number
private static int PORT = 6379;
// If the value is -1, it means no limit; If the pool has allocated maxActive jedis instances, the state of the pool is exhausted at this time.
private static int MAX_ACTIVE = 500;
// Control the maximum number of jedis instances with idle (idle) status in a pool, and the default value is also 8.
private static int MAX_IDLE = 100;
// The maximum time to wait for an available connection, in milliseconds, the default value is -1, which means never timeout. If the waiting time is exceeded, JedisConnectionException is thrown directly;
private static int MAX_WAIT = 1000;
// When calling the borrow Object method, whether to check the validity
private static Boolean TEST_ON_BORROW = false;
// When calling the return Object method, whether to check the validity
private static Boolean TEST_ON_RETURN = false;
/ / timeout
private static int TIMEOUT = 1000000;
private static JedisPool jedisPool = null;
/**
* Initialize Redis connection pool
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(MAX_ACTIVE) ;
config.setMaxIdle(MAX_IDLE);
config.setMaxWait(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
config.setTestOnReturn(TEST_ON_RETURN);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
} catch (Exception e) {
e.printStackTrace();
LoggerUtil.MyLogger.error("init jedispoll error: %s", e);
}
}
/**
* Synchronous initialization in a multi-threaded environment
*/
private static synchronized void poolInit() {
if (jedisPool == null) {
initialPool();
}
}
/**
* Release jedis resources
*
* @param jedis
*/
private static void returnResource( final Jedis jedis) {
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
/**
* destroy connection
*
* @param shardedJedis
*/
private static void returnBrokenResource(final Jedis jedis) {
try {
jedisPool.returnBrokenResource(jedis);
} catch (Exception e) {
LoggerUtil.MyLogger.error("returnBrokenResource error", e);
}
}
/**
* 推入消息到redis消息通道
*
* @param channel
* @param message
*/
public void publish(String channel, String message) {
Jedis jedis = null;
if (jedisPool == null) {
poolInit();
}
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.publish(channel, message);
}
} catch (Exception ex) {
ex.printStackTrace();
returnBrokenResource(jedis);
} finally {
returnResource(jedis);
}
}
public void close(String channel){
Jedis jedis = null;
if (jedisPool == null) {
poolInit();
}
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.publish(channel, "quit");
jedis.del(channel);
}
} catch (Exception ex) {
ex.printStackTrace();
returnBrokenResource(jedis);
} finally {
returnResource(jedis);
}
}
}
2.客户端
package com.dz.im.tools;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* message subscriber
*
* @author David
*
*/
public class SubClient {
// Redis server IP
private static String ADDR = "192.168. 0.11";
// Redis port number
private static int PORT = 6379;
// If the value is -1, it means there is no limit; if the pool has allocated maxActive jedis instances, then the state of the pool is exhausted (exhausted). ).
private static int MAX_ACTIVE = 500;
// Control the maximum number of jedis instances with idle (idle) status in a pool, and the default value is also 8.
private static int MAX_IDLE = 100;
// The maximum time to wait for an available connection, in milliseconds, the default value is -1, which means never timeout. If the waiting time is exceeded, JedisConnectionException is thrown directly;
private static int MAX_WAIT = 1000;
// When calling the borrow Object method, whether to check the validity
private static Boolean TEST_ON_BORROW = false;
// 当调用return Object方法时,是否进行有效性检查
private static Boolean TEST_ON_RETURN = false;
// 超时时间
private static int TIMEOUT = 1000000;
private static JedisPool jedisPool = null;
/**
* 初始化Redis连接池
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWait(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
config.setTestOnReturn(TEST_ON_RETURN);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
} catch (Exception e) {
e.printStackTrace();
LoggerUtil.MyLogger.error("init jedispoll error: %s", e);
}
}
/**
* Synchronized initialization in a multi-threaded environment
*/
private static synchronized void poolInit() {
if (jedisPool == null) {
initialPool( );
}
}
/**
* Release jedis resources
*
* @param jedis
*/
private static void returnResource(final Jedis jedis) {
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
/**
* Destroy the connection
*
* @param shardedJedis
*/
private static void returnBrokenResource(final Jedis jedis) {
try {
jedisPool.returnBrokenResource(jedis);
} catch (Exception e) {
LoggerUtil.MyLogger.error("returnBrokenResource error", e);
}
}
/**
* 推入消息到redis消息通道
*
* @param channel
* @param message
*/
public void subscribe(JedisPubSub listener, String channel) {
Jedis jedis = null;
if (jedisPool == null) {
poolInit();
}
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.subscribe(listener, channel);
}
} catch (Exception ex) {
ex.printStackTrace();
returnBrokenResource(jedis);
} finally {
returnResource(jedis);
}
}
}
3. Client listening
package com.dz.im.tools;
import java.text.SimpleDateFormat;
import java.util.Date;
import redis.clients.jedis.JedisPubSub;
/**
* Subscriber message processor
* @author David
*
*/
public class PrintListener extends JedisPubSub{
@Override
public void onMessage(String channel, String message) {
Date curDate=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
String time = df.format(curDate);
System.out.println("message receive:" + message + ",channel:" + channel + "..." + time);
//Here we can Unsubscribe
if(message.equalsIgnoreCase(" quit")){
this.unsubscribe(channel);
}
}
@Override
public void onPMessage(String arg0, String arg1, String arg2) {
}
@Override
public void onPSubscribe(String arg0, int arg1) {
}
@Override
public void onPUnsubscribe(String arg0, int arg1) {
}
@Override
public void onSubscribe(String arg0, int arg1) {
}
@Override
public void onUnsubscribe(String arg0, int arg1) {
}
}
4.服务端测试类
package com.dz.im.tools;
import org.apache.commons.lang.RandomStringUtils;
public class PubSubTestMain {
public static void main(String[] args) throws Exception {
PubClient pubClient = new PubClient();
String channel = "public-test";
int i = 0;
while (i < 200) {
String message = "测试的所得税法大的"+RandomStringUtils.random(6, true, true);
pubClient.publish(channel, message);
i++;
Thread.sleep(1000);
}
}
}
5. Client test class
package com.dz.im.tools;
import redis.clients.jedis.JedisPubSub;
public class Demo {
private static final String channel="public-test";
public static void main(String[] args) {
try {
while(true){
SubClient subClient = new SubClient();
JedisPubSub listener = new PrintListener();
subClient.subscribe(listener, channel);
}
} catch (Exception e) {
e.printStackTrace ();
}
}
}
Refer to this article http://shift-alt-ctrl.iteye.com/blog/1867454