启动的时候获取本机的公网ip去注册到nacos上
思路大概是: 启动的时候加载完配置文件后,设置配置文件中的spring.cloud.nacos.discovery.ip值为本机的公网ip
那么第一个问题来了,我怎么知道自己的公网ip呢?
开发过程中常见的方式就是从请求中取,但是如果是通过nginx代理的服务就得让nginx代理的时候将真实访问ip也代理过去,那我们是否就可以从nginx来获取呢?
于是我在我的nginx上加了这个配置(配置在server中)
nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
server {
listen 80;
server_name centos.jiangzt.cn;
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
location = /getIp{
return 200 "$remote_addr";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
这时候你访问 域名/getIp 就会直接返回访问端的IP地址了
这个公网ip来源解决了,接下来就是把ip更新到配置中去
增加一个listener:
public class AfterConfigListener implements SmartApplicationListener, Ordered {
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
return(ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(aClass) ||
ApplicationPreparedEvent.class.isAssignableFrom(aClass) );
}
@Override
public int getOrder() {
return(ConfigFileApplicationListener.DEFAULT_ORDER + 1);
}
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
RestTemplate restTemplate=new RestTemplate();
ResponseEntity<String> response=restTemplate.getForEntity("https://xxxx.xxx/getIp",String.class);
String currenIp=response.getBody();
if (applicationEvent instanceof ApplicationEnvironmentPreparedEvent)
{
System.setProperty("spring.cloud.nacos.discovery.ip", currenIp);
}
}
}
然后在启动类的main方法中注册这个listener:
SpringApplication springApplication = new SpringApplication(xxxxApplication.class);
springApplication.addListeners(new AfterConfigListener());
springApplication.run(args);
这时候你启动这个服务的时候,在服务最后你就能发现输出了一行:
(NacosServiceRegistry.java:65)- nacos registry, DEFAULT_GROUP xxx-xxx-xxx xxx.xxx.xxx.xxx:port register finished
这时候你到nacos控制台上就能发现,ip已经是公网ip了,两个服务之间就不用在同个局域网内了
参考
- https://juejin.cn/post/7111912514744500238