Redis实现消息队列(1)——通过Jedis发布和订阅消息

 1.  引入jar

             
			org.springframework.boot
			spring-boot-starter-data-redis
	      
              
			io.github.xiaoyudeguang
			easy-core
			1.2.23-RELEASE
	    
	    
			redis.clients
			jedis
	    

 2. JedisUtils工具类

@EasyBean(todo = { "" })
public class JedisUtils implements IHandlerOnRefreshed, IHandlerOnChanged{

	private static JedisPool jedisPool;
	
	@Value("${spring.redis.host}")
	private String reids_host;
	
	@Value("${spring.redis.port}")
	private int reids_port;
	
	@Value("${spring.redis.timeout}")
	private String timeout;
	
	@Value("${spring.redis.password}")
	private String password;
	
	@Value("${spring.redis.database}")
	private int database;
	
	@Override
	public void doOnRefreshed(ApplicationContext context) throws Exception {
		 jedisPool = new JedisPool(new JedisPoolConfig(), reids_host, reids_port, 100000, password, database);
	}
	
	@Override
	public void doOnChanged(ApplicationContext context) throws Exception {
		jedisPool.close();
	}
	
	public static Long publish(String channel, Object message ) {
		return jedisPool.getResource().publish(channel, JSON.toJSONString(message));
	} 

	public static void subscribe(JedisPubSub jedisPubSub, String... channels) {
		jedisPool.getResource().subscribe(jedisPubSub, channels);
	}
}

3.发布消息

JedisUtils.publish("自定义通道名称", "消息内容");

4. 订阅消息

@ApplicationRefreshedBean(todo = { "Redis消息消费者" }, order = 3)
public class MsgSubscriber extends JedisPubSub implements IHandlerOnRefreshed {

	@Override
	public void doOnRefreshed(ApplicationContext context) throws Exception {
		ThreadManager.execute(new Thread(() -> {
			JedisUtils.subscribe(this, "自定义通道名称");
		}));
	}

	@Override
	public void onMessage(String channel, String message) {
		LogUtils.info(this, channel + "订阅消息", message);
	}
}

 

你可能感兴趣的:(Redis)