Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Actuator Health Checking #808

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,29 @@
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

import me.zhengjie.modules.security.security.PromethuseResponseFilter;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
import org.springframework.boot.actuate.endpoint.web.WebEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
Expand All @@ -30,6 +49,7 @@
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
Expand All @@ -40,6 +60,7 @@
*/
@Configuration
@EnableWebMvc
@EnableSwagger2
public class ConfigurerAdapter implements WebMvcConfigurer {

/** 文件配置 */
Expand Down Expand Up @@ -77,6 +98,11 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
List<MediaType> supportMediaTypeList = new ArrayList<>();
supportMediaTypeList.add(MediaType.APPLICATION_JSON);
supportMediaTypeList.add(MediaType.TEXT_PLAIN);

// Promethuse sends request with header 'Accept: application/openmetrics-text; version=1.0.0; charset=utf-8'
MediaType openMetrics = MediaType.parseMediaType("application/openmetrics-text;version=1.0.0;charset=utf-8");
supportMediaTypeList.add(openMetrics);
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
Expand All @@ -85,4 +111,65 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
converter.setDefaultCharset(StandardCharsets.UTF_8);
converters.add(converter);
}


/**
* 注册endpoints,解决springboot升级到2.6.x之后,actuator error problems
*
* @param webEndpointsSupplier the web endpoints supplier
* @param servletEndpointsSupplier the servlet endpoints supplier
* @param controllerEndpointsSupplier the controller endpoints supplier
* @param endpointMediaTypes the endpoint media types
* @param corsProperties the cors properties
* @param webEndpointProperties the web endpoint properties
* @param environment the environment
* @return the web mvc endpoint handler mapping
*/
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier,
ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping = shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);

return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
shouldRegisterLinksMapping);
}

/**
* shouldRegisterLinksMapping
* @param webEndpointProperties webEndpointProperties
* @param environment environment
* @param basePath /
* @return boolean
*/
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties,
Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath)
|| ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}


/**
* 配置过滤器
*
* @return
*/
@Bean
public FilterRegistrationBean someFilterRegistration()
{
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new PromethuseResponseFilter());// 配置一个返回值过滤器
registration.addUrlPatterns("/actuator/prometheus");
registration.addInitParameter("paramName", "paramValue");
registration.setName("responseFilter");
return registration;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package me.zhengjie.config;


import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;


/**
* 返回值输出代理类
*
* @Title: ResponseWrapper
* @Description:
* @author fei
* @date 2023-07-26
*/
public class ResponseWrapper extends HttpServletResponseWrapper
{

private ByteArrayOutputStream buffer;

private ServletOutputStream out;

public ResponseWrapper(HttpServletResponse httpServletResponse)
{
super(httpServletResponse);
buffer = new ByteArrayOutputStream();
out = new WrapperOutputStream(buffer);
}

@Override
public ServletOutputStream getOutputStream()
throws IOException
{
return out;
}

@Override
public void flushBuffer()
throws IOException
{
if (out != null)
{
out.flush();
}
}

public byte[] getContent()
throws IOException
{
flushBuffer();
return buffer.toByteArray();
}

class WrapperOutputStream extends ServletOutputStream
{
private ByteArrayOutputStream bos;

public WrapperOutputStream(ByteArrayOutputStream bos)
{
this.bos = bos;
}

@Override
public void write(int b)
throws IOException
{
bos.write(b);
}

@Override
public boolean isReady()
{

// TODO Auto-generated method stub
return false;

}

@Override
public void setWriteListener(WriteListener arg0)
{

// TODO Auto-generated method stub

}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.modules.security.service.UserCacheManager;
import me.zhengjie.utils.enums.RequestMethodEnum;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand Down Expand Up @@ -98,6 +100,8 @@ protected void configure(HttpSecurity httpSecurity) throws Exception {
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
// .antMatchers("/login").permitAll()
// 静态资源等等
.antMatchers(
HttpMethod.GET,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package me.zhengjie.modules.security.security;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;

import me.zhengjie.config.ResponseWrapper;

public class PromethuseResponseFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse)response);//转换成代理类
filterChain.doFilter(request, wrapperResponse);

byte[] content = wrapperResponse.getContent();//获取返回值
if (content.length > 0) {
String jsonString = new String(content);
Object plaObject = JSON.parse(jsonString);
//把返回值输出到客户端
ServletOutputStream out = response.getOutputStream();
// Prometheus actuator endpoint should produce a text/plain response
// https://github.com/spring-projects/spring-boot/issues/28446
response.setContentType("text/plain");
out.write(plaObject.toString().getBytes());
out.flush();
out.close();
}

}
}
35 changes: 35 additions & 0 deletions eladmin-system/src/main/resources/config/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,38 @@ file:
# 文件大小 /M
maxSize: 100
avatarMaxSize: 5

management:
# 可以指定暴露哪些actuator服务,'*'为全部,注意加上引号,被注释的写法表示只允许health,info, metrics, shutdown
endpoints:
web:
exposure:
include: health,info, metrics, shutdown, prometheus
# include: '*' # all
# default: http://localhost:8000/actuator/*
# base-path: http://localhost:8000/${base-path}/*
# base-path: /check (web.base-path)
endpoint:
# 通过/actuator/shutdown停止服务
shutdown:
enabled: true
# 显示health的详细内容
health:
show-details: always
info: # 显示任意的应用信息,默认关闭,如果是更低一些的版本默认是开启的
env:
enabled: true
# 自定义/actuator/info中的各种内容,可以自定义,也可以取默认的一些系统/服务环境变量
info:
app:
encoding: "@project.build.sourceEncoding@"
java:
source: "@java.version@"
target: "@java.version@"
build:
artifact: @project.artifactId@
name: @project.name@
description: @project.description@
pomVersion: @project.version@
# 甚至可以自定义test
test: 'I love Spring Boot'
18 changes: 17 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,16 @@
<artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<!--监控sql日志-->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
Expand All @@ -110,7 +120,13 @@
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.43</version>
<!-- <scope>runtime</scope> -->
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

<!-- druid数据源驱动 -->
Expand Down