参考:https://zhuanlan.zhihu.com/p/48490362
问题:MQ队列的要求是:不同的服务对应不同的MQ队列。
解决的方法1:获取服务的IP地址,用于区分:
/**
* 获取本机的局域网ip地址,兼容Linux
*/
public static String getLocalHostIP() {
String localHostAddress = "";
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = allNetInterfaces.nextElement();
Enumeration<InetAddress> address = networkInterface.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress inetAddress = address.nextElement();
if (inetAddress != null && inetAddress instanceof Inet4Address && !inetAddress.getHostAddress().startsWith("127.0")) {
localHostAddress = inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
log.error(ex.getMessage());
localHostAddress = String.valueOf(new Random().nextInt(10000));
}
return localHostAddress;
}
解决方法2: 记录在redis启动的队列,有效期设置为120S。
@Slf4j
@Service
public class TestConfig {
@Autowired
private IRedisService redisService;
public static String socketMqKey = null;
public String getUniqueKey(){
String key = "activity.websocket.queue_";
for(int i = 0;i < 20;i++) {
Boolean lock = redisService.lock(key + i, 1, 120L, TimeUnit.SECONDS);
if(lock){
log.info("mqqueer成功:" + i);
socketMqKey = key + i;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
log.info("续约");
redisService.expire(socketMqKey,120L);
}
},10 * 1000,10 * 1000);
return socketMqKey;
}else{
log.info("mqqq失败:" + i);
}
}
new BusinessException("mq队列异常");
return null;
}
}
配置
消费者:
@RabbitHandler
@RabbitListener(queues = "#{webSocketQueue1.name}",concurrency="10")
public void consumer(参数类型 参数) {
//业务代码
}