1. 봄 부팅 관리자 무엇입니까
로 봄 부팅 관리자 codecentric 관리하고 봄 부팅 프로젝트를 모니터링 할 수 있습니다 봄 부팅 관리자를 사용하여 오픈 소스 프로젝트의 개발 조직. 그것은 두 부분으로 클라이언트와 서버로 나누어 져 있습니다, 당신의 봄 부팅 HTTP 인터페이스 응용 프로그램에 추가 된 클라이언트는 빗물 배수관 관련 정보를 증가하고,이 단계는 서버에 직접 수행 할 수 있습니다 등록 할 수 있습니다 봄 부팅 관리자 서버에 등록 유레카 또는 영사를 통해 등록한다. Vue.js 시각 렌더링 프로그램에 의해 봄 부팅 관리 서버 모니터링 정보. 그리고 이벤트 알림 작업의 다양한 지원합니다.
2. 봄 부팅 관리자 서버
봄 부팅 관리자 서버가 봄 부팅 프로젝트를 기반으로, 여기에 언급하지 않는 봄 부트 프로젝트를 만드는 방법, 당신은 이전 기사 또는에서 참조 할 수 https://start.spring.io/ 스프링 부트 프로젝트를 직접 가져옵니다.
2.1. 추가 의존
그냥 웹 의존성과 스프링 부팅 관리자 - 스타터 서버 종속성을 추가합니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>
2.2. 시작 구성
다음과 같은 클라이언트 포트가없는 충돌을 위해 그리고, 포트 번호는 9090입니다 수정합니다.
server:
port: 9090
추가 @EnableAdminServer
봄 부팅 관리 서버 기능을 활성화하기 위해 주석을.
@EnableAdminServer
@SpringBootApplication
public class SpringbootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAdminServerApplication.class, args);
}
}
서버는 당신이 봄 부팅 관리 서버의 페이지를 볼 수있는 프로젝트 방문을 시작하도록 구성되었습니다.
3. 봄 부팅 관리자 클라이언트
아직 여기에만 의존 봄 부팅 관리자 고객의 요구를 추가 할 필요가 언급하지 않는 봄 부트 프로젝트를 만들고 프로젝트의 시작은 정보에 대한 액세스와 관련된 API 인터페이스를 증가시킬 것이다. 그리고 봄 부팅 구성 파일의 구성 봄 부팅 관리자 서버, 그것은 모니터링 할 수 있습니다.
3.1 클라이언트는 의지
pom.xml 파일
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>
<!-- Lombok 工具,与 admin client 无关 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
3.2 클라이언트 구성
클라이언트가 성공적으로 서버에 등록 할 수 있도록하기 위해 주요 클라이언트 구성, 당신은 클라이언트 URL 관련 정보와 봄 부팅 관리 서버 서버 응용 프로그램 종료를 구성해야합니다.
server:
port: 8080
spring:
application:
# 应用名称
name: sjfx-api-search
jmx:
enabled: true
boot:
admin:
client:
# 服务端 url
url: http://127.0.0.1:9090
instance:
# 客户端实例 url
service-url: http://127.0.0.1:8080
prefer-ip: true
# 客户端实例名称
name: sjfx-api-search
management:
endpoints:
web:
exposure:
# 暴漏的接口 - 所有接口
include: "*"
구성은 include: "*"
생산 환경, 대중에게 인터페이스를 선택 확신한다, 모든 포트를 공개했다.
봄 부팅 관리자 그래서 20 초마다 한 번 코드 출력 현재 시간, 로그 수준으로 정기적 인 일정을 추가, 일반 작업 응용 프로그램을 얻을 수있는 INFO
다음과 같은 일반 작업 및 테스트를 모니터링 로그인합니다.
@Slf4j
@SpringBootApplication
@EnableScheduling
public class SpringbootAdminClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAdminClientApplication.class, args);
}
@Scheduled(cron = "0/20 * * * * ?")
public void run20s() {
log.info("定时任务:{}", LocalDateTime.now());
}
}
3.3. 클라이언트 실행
인터페이스의 클라이언트 빗물 배수관 관련 작동 상태를 시작하고 자동으로 서버 구성에 대한 등록 정보를 보낼 수 있습니다.
다음은 클라이언트의 부트 로그는 다음과 같습니다
2019-12-21 22:45:32.878 INFO 13204 --- [ main] n.c.b.SpringbootAdminClientApplication : Starting SpringbootAdminClientApplication on DESKTOP-8SCFV4M with PID 13204 (D:\IdeaProjectMy\springboot-git\springboot-admin\springboot-admin-client\target\classes started by 83981 in D:\IdeaProjectMy\springboot-git\springboot-admin)
2019-12-21 22:45:32.881 INFO 13204 --- [ main] n.c.b.SpringbootAdminClientApplication : No active profile set, falling back to default profiles: default
2019-12-21 22:45:33.627 INFO 13204 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-12-21 22:45:33.634 INFO 13204 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-12-21 22:45:33.634 INFO 13204 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2019-12-21 22:45:33.706 INFO 13204 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-12-21 22:45:33.706 INFO 13204 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 797 ms
2019-12-21 22:45:33.850 INFO 13204 --- [ main] o.s.b.a.e.web.ServletEndpointRegistrar : Registered '/actuator/jolokia' to jolokia-actuator-endpoint
2019-12-21 22:45:33.954 INFO 13204 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-21 22:45:34.089 INFO 13204 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService
2019-12-21 22:45:34.117 INFO 13204 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
2019-12-21 22:45:34.120 INFO 13204 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 15 endpoint(s) beneath base path '/actuator'
2019-12-21 22:45:34.162 INFO 13204 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-12-21 22:45:34.163 INFO 13204 --- [ main] n.c.b.SpringbootAdminClientApplication : Started SpringbootAdminClientApplication in 1.563 seconds (JVM running for 2.131)
2019-12-21 22:45:34.271 INFO 13204 --- [gistrationTask1] d.c.b.a.c.r.ApplicationRegistrator : Application registered itself as 6bcf19a6bf8c
2019-12-21 22:45:34.293 INFO 13204 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-12-21 22:45:34.294 INFO 13204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-12-21 22:45:34.300 INFO 13204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 6 ms
(가) 로그의 시작부터 Exposing 15 endpoint(s) beneath base path '/actuator'
이, 당신은 폭풍 드레인 (15) 볼 수 있습니다 /actuator
응답 결과를 볼 API 인터페이스, 직접 액세스 할 수.
로그에서 Application registered itself as 6bcf19a6bf8c
당신은 클라이언트가 성공적으로 등록 된 것을 볼 수 있습니다. 서버 봐 등록까지의 응용 프로그램의 예를 볼 수 있습니다.
4. 봄 부팅 관리자 기능
적용 사례는 온라인 자세히 모니터링 및 관리 응용 프로그램 예제 페이지로 이동할 수 있습니다, 모니터링 페이지를 클릭, 그것은 Vue.js 웹 존재를 달성하는 것입니다.
많은 봄 부팅 관리 서버는이 섹션에서 설명 모니터링 할 수 있습니다, 사용하기 어려운 일이 아니다, 기능을 모니터링 할 수 있습니다 :
- 시간, 쓰레기 수거 빈도와 스레드의 수, 메모리 사용 경향으로 실행되는 응용 프로그램.
- 어플리케이션 성능 모니터링 또는 톰캣 JVM 파라미터를 선택하여, 전류 값을 확인.
- 환경 모니터링 애플리케이션,보기 시스템 환경 변수, 응용 프로그램 구성 매개 변수를 자동 구성 매개 변수를 설정합니다.
- 应用 bean 管理,查看 Spring Bean ,并且可以查看是否单例。
- 应用计划任务,查看应用的计划任务列表。
- 应用日志管理,动态更改日志级别,查看日志。
- 应用 JVM 管理,查看当前线程运行情况,dump 内存堆栈信息。
- 应用映射管理,查看应用接口调用方法、返回类型、处理类等信息。
上面提到的日志管理,可以动态的更改日志级别,以及查看日志。默认配置下是只可以动态更改日志级别的,如果要在线查看日志,就需要手动配置日志路径了。
客户端上可以像下面这样配置日志路径以及日志高亮。
# 配置文件:application.yml
logging:
file:
name: boot.log
pattern:
# 日志高亮
file: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx'
下面是在 Spring Boot Admin 监测页面上查看的客户端应用日志。
5. Spring Boot Admin 进阶
5.1. 邮件通知
Spring Boot Admin Server 支持常见的通知方式,比如邮件通知、电报通知、PagerDuty 通知等,下面将会演示常见的通知方式 - 邮件通知,最后也会演示如何通过监听时间进下设置自定义通知方式。
Spring Boot Admin Server 的邮件通知通过 Thymeleaf 模板发送 HTML 格式的电子邮件。因此,想要使用邮件通知首先要引入 Thymeleaf 依赖以及 spring-boot-starter-mail
依赖,并配置邮件发送者信息和接受者信息。
1. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Thymeleaf 模版,用于发送模版邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 配置邮件
主要设置发送者信息和接收者信息。
spring:
boot:
admin:
notify:
mail:
# 逗号分隔的邮件收件人列表
to: [email protected]
# 开启邮箱通知
enabled: true
# 不需要发送通知的状态:从状态A:到状态B
ignore-changes: {"UNKNOWN:UP"}
# 逗号分隔的抄送收件人列表
cc: [email protected]
# 发件人
from: Spring Boot Admin<[email protected]>
# 邮件发送者信息
mail:
host: smtp.126.com
port: 25
username: [email protected]
default-encoding: utf-8
password: xxxx
如果想了解更多关于 Spring Boot 邮件发送信息,可以参考 Spring Boot 系列文章第十三篇。
配置好邮件通知之后,重启服务端和客户端,等客户端注册到服务端之后直接终止客户端的运行,稍等片刻就可以在配置的通知接收邮箱里收到客户端实例下线通知了。
邮件通知使用的模板存放在 server 依赖的 classpath:/META-INF/spring-boot-admin-server/mail/status-changed.html 路径,如果想要自定义模板内容。可以拷贝这个文件放到自己的 templates 目录下,修改成自己想要的效果,然后在配置中指定自定义模板路径。
spring:
boot:
admin:
notify:
mail:
# 自定义邮件模版
template: classpath:/templates/notify.html
5.2 自定义通知
自定义通知只需要自己实现 Spring Boot Admin Server 提供的监听通知类即可,下面会演示如何在实例状态改变时输出实例相关信息。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import de.codecentric.boot.admin.server.notify.LoggingNotifier;
import reactor.core.publisher.Mono;
@Component
public class CustomNotifier extends AbstractEventNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingNotifier.class);
public CustomNotifier(InstanceRepository repository) {
super(repository);
}
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
return Mono.fromRunnable(() -> {
if (event instanceof InstanceStatusChangedEvent) {
LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
((InstanceStatusChangedEvent)event).getStatusInfo().getStatus());
} else {
LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),
event.getType());
}
});
}
}
5.2. 访问限制
上面提到过,因为客户端增加了暴漏运行信息的相关接口,所以在生产环境中使用存在风险,而服务端没有访问限制,谁的可以访问也是不合理的。
下面将会为客户端和服务端分别增加访问限制,客户端主要是限制敏感接口的访问权限,服务端则是全局的访问限制。这些访问限制都通过 spring 安全框架 security 来实现,所以首先要为客户端和服务端都增加 maven 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1. 服务端
在引入安全框架依赖之后,需要配置访问控制,比如静态资源不需要限制,登录登出页面指定等。
import java.util.UUID;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import io.netty.handler.codec.http.HttpMethod;
@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final AdminServerProperties adminServer;
public SecuritySecureConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeRequests()
.antMatchers(this.adminServer.path("/assets/**")).permitAll()
.antMatchers(this.adminServer.path("/login")).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage(this.adminServer.path("/login")).successHandler(successHandler).and()
.logout().logoutUrl(this.adminServer.path("/logout")).and()
.httpBasic().and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
new AntPathRequestMatcher(this.adminServer.path("/instances"), HttpMethod.POST.toString()),
new AntPathRequestMatcher(this.adminServer.path("/instances/*"), HttpMethod.DELETE.toString()),
new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))
)
.and()
.rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600);
// @formatter:on
}
// 代码配置用户名和密码的方式
// Required to provide UserDetailsService for "remember functionality"
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER");
// }
}
在 application.yml 配置文件中配置用户名和密码。
spring:
security:
user:
name: user
password: 123
重启服务端,再次访问就需要用户名和密码进行登录了。
2. 客户端
客户端在引入安全框架之后,也需要配置访问权限,主要是配置哪些路径可以访问,哪些路径访问需要登录限制,默认所有接口都需要登录限制。
同样的,客户端应用也需要在配置中配置客户端应用对于敏感接口的登录用户和密码,同时需要配置 Spring Boot Admin Server 的访问用户和密码,还要把自身的用户和密码注册时告诉服务端,不然服务端不能获取到监测数据。
spring:
security:
user:
# 客户端敏感接口用户和密码
name: client
password: 123
application:
# 应用名称
name: sjfx-api-search
jmx:
enabled: true
boot:
admin:
client:
# 服务端 url
url: http://127.0.0.1:9090
instance:
# 客户端实例 url
service-url: http://127.0.0.1:8080
prefer-ip: true
# 客户端实例名称
name: sjfx-api-search
metadata:
# 客户端自身的用户和密码告诉服务端
user.name: client
user.password: 123
# 服务端用户名密码
username: user
password: 123
客户端敏感接口访问测试。
到这里,客户端的敏感接口访问需要登录,服务端的管理页面也需要登录,客户端和服务端的访问控制已经完成了。
: 텍스트 코드에 업로드 된 github.com/niumoo/springboot/tree/master/springboot-admin
참고 :
https://github.com/codecentric/spring-boot-admin
https://codecentric.github.io/spring-boot-admin/current/
<끝>
웹 사이트 : https://www.codingme.net
이 기사를 즐길 경우, 공용 수를 집중할 수 있습니다, 함께 성장.
어떤 대중의 관심은 핵심 자바 인터뷰를 마무리 및 핵심 정보의 전체 네트워크 섹시한 지식 자원에 대한 일상적인 접근에 응답 할 수 없습니다.