其它

redis RedisTemplate实现队列功能

2021-01-28 00:29:01 阅读数 5608 收藏 0

发布消息端代码:

/**
* 发布消息
* @param id
* @return
*/
@RequestMapping("/sendMessage/{id}")
public String sendMessage(@PathVariable String id) {
	redisTemplate.convertAndSend("msg","哈哈哈,redis 订阅信息");
	return "";
}

接受消息的实体类:

/**
 * 接收消息的实体类 
 */
@Component
public class RedisMessage implements MessageListener {
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
		String msg = serializer.deserialize(message.getBody());
		 System.out.println("接收到的消息是:" + msg);
	}
}

使用list:

/**获取RedisTemplate操作方式*/
ListOperations operation = redisTemplate.opsForList();
operation.leftPush(template_Queue, data);
System.out.println("主线程休眠10秒......");
Thread.sleep(10000);
Object strJson = operation.rightPop(template_Queue,10, TimeUnit.SECONDS);
System.out.println("队列读出数据:");
System.out.println(strJson);
System.out.println("测试结束......");