spring boot admin 监控和服务部署到同一台服务器查看日志没有什么问题。但是当spring boot服务进行分布式部署时,这个时候会存在如下情况,查看不了日志。
这个时候,我们需要进行如下配置操作,
1、添加属性版
1-1、yml文件修改
xxxx:
server:
ip:
spring:
boot:
admin:
client:
instance:
name: xxxx服务_${spring.profiles.active}
id: ${random.uuid}
prefer-ip: true
service-base-url: http://${xxxx.server.ip}:${server.port}
1-2、后台代码
public class xxxxService {
public static void main(String[] args) {
System.setProperty("xxxx.server.ip",ServerIPFileUtils.getServerIp());
SpringApplication.run(xxxxService.class, args);
}
}
2、新增配置文件版本
2-1、配置文件操作
spring:
boot:
admin:
client:
instance:
name: xxxx服务_${random.int[1,10]}
id: ${random.uuid}
prefer-ip: true
config:
import:
- optional:/xxx/xxx/xx-xx/server_ip.yml #引入外部文件设置spring boot server 服务器ip地址.
2-1-1、server_ip.yml文件内容
spring:
boot:
admin:
client:
instance:
service-base-url: http://xxxxx:${server.port}
2-2、动态生成server_ip.yml
private static final String IP_FILE_CONTENT="spring:\n" +
" boot:\n" +
" admin:\n" +
" client:\n" +
" instance:\n" +
" service-base-url: http://local_ip_server_name:${server.port}";
private static final String SERVER_FILE_NAME = "/server_ip.yml";
public static void createServerFile(String filePath ) {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
log.debug("穿件文件夹{}成功",file.getParentFile().getAbsolutePath());
}
if(file.exists()){
log.info("文件{}存在,不需要重复生成",filePath);
return;
}else {
log.info("文件不存在,首次生成文件,path={}",file.getAbsolutePath());
}
try (OutputStream outputStream = new FileOutputStream(file);) {
String content=IP_FILE_CONTENT.replace("local_ip_server_name",getServerIp() );
outputStream.write(content.getBytes());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 获取当前部署环境主机IP
* @return
*/
public static String getServerIp() {
try {
String hostName = Inet4Address.getLocalHost().getHostName();
InetAddress inetAddress2[] = Inet4Address.getAllByName(hostName);
for (InetAddress add:inetAddress2){
if(add.isSiteLocalAddress()){
log.debug("address={},hostname={}",add.getHostAddress(),add.getHostName());
return add.getHostAddress();
}
}
} catch (UnknownHostException e) {
log.error(e.getMessage(),e);
}
return DEFAULT_IP;
}
2-3、服务启动生成server_ip.ymal文件
@SpringBootApplication
@ComponentScan({"com.xxx.xx.xxx.*"})
@MapperScan({"com.xx.xx.xx.xx.*.mapper"})
public class MQApplication {
private static String filePath;
//server_ip。ymal文件生成地址
@Value("${xx.xx.ip-server-file}")
private String ipServerFile;
@PostConstruct
public void init(){
filePath = ipServerFile;
}
public static void main(String[] args) {
SpringApplication.run(XXApplication.class,args);
ServerIPFileUtils.createServerFile(filePath);
}
}
以上操作为个人实现方案,仅供参考,大家如果还有更好的方式,欢迎评论区留言一起讨论。