在我的应用程序中,我使用多个消费者从 Redis 的发布者接收消息。但现在的问题是数据丢失和重复数据,我的意思是多个消费者接收相同的消息。我如何在 Redis 中解决这个问题?并且还可以在 java 中提供示例,我是 redis 消息传递的新手。请帮助我。
这是我的接收器
@Configuration
@EnableScheduling
public class ScheduledRecevierService {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Bean
RedisConnectionFactory redisConnectionFactory() {
LOGGER.info("in redisConnectionFactory");
JedisConnectionFactory redis = new JedisConnectionFactory();
redis.setHostName("ipaddress");
redis.setPort(6379);
return redis;
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
LOGGER.info("in template");
return new StringRedisTemplate(connectionFactory);
}
@Scheduled(fixedRate = 1000)
public void getScheduledMessage() {
StringRedisTemplate template = template(redisConnectionFactory());
System.out.println("The time is now " + dateFormat.format(new Date()));
LOGGER.info("Sending messages...");
String message = template.opsForList().leftPop("point-to-point-test"); // latch.await();
// template.convertAndSend("chat", "Hello from Redis! count: " + i);
LOGGER.info("Got message " + message + " from chat1 channel"); //
}
}
我在多个消费者实例中运行此应用程序。我的队列“点对点测试”有 1000 条消息,我观察到在多个服务器日志中读取相同的消息。
能否用java在redis中实现点对点协议(protocol)通信?
redis 中的 RPOPLPUSH 命令解决了这个问题?如果是,请在 java 中发布一些示例。
最近几天我一直在努力解决 redis 消息传递中的这些问题,请帮助我
最佳答案
使用 Redis 事务确保所有命令按顺序执行 http://redis.io/topics/transactions
使用 Jedis 作为 java 客户端库,查看其在事务上的使用测试 https://github.com/xetorthio/jedis/blob/master/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java
关于java - redis消息多消费者情况下数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26136313/