在项目开发过程中因为全部的开发人员启动时使用的环境都是测试环境,这样启动时各开发人员的服务器都注册到了RocketMq生产端,RocketMQ推送的消息不知道被哪台注册的服务器消费对开发人员自测及测试环境测试造成了困难。消费端不在同一个项目组无法要求生产者指定某台服务器发送消息。针对这些情况,从消费端出发解决方案如下:
1.增加开关只有开关打开的才允许指定IP的客户注册到生产者。适配测试环境。
2.开关关闭适配准生产环境允许所有注册的消费者消费消息。
package com.example.apollo.annotation;
import com.example.apollo.registrar.DynamicRocketMQRegistrar;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(DynamicRocketMQRegistrar.class)
public @interface EnableRemoteRocketMQ {
}
package com.example.apollo.registrar;
import cn.hutool.core.util.StrUtil;
import com.sun.tools.javac.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.type.AnnotationMetadata;
import java.net.Inet4Address;
import java.net.UnknownHostException;
@Slf4j
public class DynamicRocketMQRegistrar implements ImportSelector, EnvironmentPostProcessor, Ordered {
/**
* 使用static修饰是因为ImportSelector,EnvironmentPostProcessor在上下文中加载的顺序不一致
*/
private static String whiteIp = "";
private static String on = "";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if(StrUtil.isEmpty(on)){
on = environment.getProperty("dynamic.switch");
}
}
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if("Y".equals(on)){
if(StrUtil.isEmpty(whiteIp)){
return new String[]{RocketMQAutoConfiguration.class.getName()};
}else{
String ip = "";
try {
ip = Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("获取IP异常",e);
}
if(whiteIp.equals(ip)){
return new String[]{RocketMQAutoConfiguration.class.getName()};
}else{
return new String[0];
}
}
}else{
return new String[]{RocketMQAutoConfiguration.class.getName()};
}
}
@Override
public int getOrder() {
return 9999;
}
}
在resource目录下的META-INF目录下新增spring.factories文件,配置如下
org.springframework.boot.env.EnvironmentPostProcessor=com.example.apollo.registrar.DynamicRocketMQRegistrar
这样当Apollo配置的开关为开的时候客户通过读取apollo配置的白名单IP使指定IP白名单的Rocket消费端注册到Rocket生产端。