Eureka注册中心通用写法和配置
-
下面简单介绍下 Eureka 注册中心的通用写法
-
新建个空项目,pom 中加入如下依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.5.12</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId><version>3.0.5</version></dependency><dependency><groupId>at.twinformatics</groupId><artifactId>eureka-consul-adapter</artifactId><version>1.3.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId><version>2.5.8</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-actuator</artifactId><version>2.7.18</version></dependency>
</dependencies>
- 新建个包路径:com.xdr630.registry.config
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Value("${eureka.security.enabled:false}")private boolean securityEnabled;@Overrideprotected void configure(HttpSecurity http) throws Exception {// 关闭csrf设置http.csrf().disable();if(!securityEnabled){// 配置不需要登录验证http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll();return;}super.configure(http);}
}
- 在 com.xdr630.registry 包下,新建启动类
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {private static final Logger log = LoggerFactory.getLogger(EurekaServerApplication.class);public static void main(String[] args) {SpringApplication app = new SpringApplication(EurekaServerApplication.class);app.addListeners(new ApplicationPidFileWriter(), new WebServerPortFileWriter());Environment env = app.run(args).getEnvironment();logApplicationStartup(env);}private static void logApplicationStartup(Environment env) {String protocol = "http";if (env.getProperty("server.ssl.key-store") != null) {protocol = "https";}String serverPort = env.getProperty("server.port");String contextPath = env.getProperty("server.servlet.context-path");if (StringUtils.isEmpty(contextPath)) {contextPath = "/";}String hostAddress = "localhost";try {hostAddress = InetAddress.getLocalHost().getHostAddress();} catch (UnknownHostException e) {log.warn("The host name could not be determined, using `localhost` as fallback");}// @formatter:offlog.info("\n----------------------------------------------------------\n\t" +"Application '{}' is running! Access URLs:\n\t" +"Local: \t\t{}://localhost:{}{}\n\t" +"External: \t{}://{}:{}{}\n\t" +"Profile(s): \t{}\n----------------------------------------------------------",env.getProperty("spring.application.name"),protocol,serverPort,contextPath,protocol,hostAddress,serverPort,contextPath,env.getActiveProfiles());// @formatter:on}
}
- resources 下 application.yml
spring:application:name: eureka-registry# 配置认证用户名和密码,不配置系统会随机生成security:user:name: user #认证用户名password: 123456 #认证密码
server:port: 8081eureka:server:#关闭自我保护模式enableSelfPreservation: false#主动失效时间,默认60*1000evictionIntervalTimerInMs: 5000#禁用readOnlyCacheMapuseReadOnlyResponseCache: falseclient:registerWithEureka: falsefetchRegistry: falseserviceUrl:#defaultZone: http://localhost:8081/eureka/ #未开启认证时urldefaultZone: http://user:123456@localhost:8081/eureka/ #开启认证时urlmanagement:endpoints:web:exposure:include: "*" #["configprops", "env", "health", "info", "jhimetrics", "logfile", "loggers", "threaddump"]endpoint:health:show-details: always #when_authorizedenv:enabled: falsemappings:enabled: falseconfigprops:enabled: falseheapdump:enabled: falseloggers:enabled: falseconditions:enabled: falsebeans:enabled: falsemetrics:enable:http: truejvm: truelogback: trueprocess: truesystem: truedistribution:percentiles-histogram:all: truepercentiles:all: 0, 0.5, 0.75, 0.95, 0.99, 1.0
- logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration scan="false"><include resource="org/springframework/boot/logging/logback/defaults.xml" /><property name="APP_NAME" value="registry-eureka"/><property name="LOG_FILE" value="${BUILD_FOLDER:-logs}/${APP_NAME}"/><property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] %level [${APP_NAME:-},%X{traceId},%X{spanId},%X{parentId}] ${PID:- } --- [%thread] %-40.40class{39} %L: %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} \n"/><appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender"><file>${LOG_FILE}.log</file><rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"><fileNamePattern>${LOG_FILE}-%d{yyyyMMdd}.log.%i</fileNamePattern><maxFileSize>100MB</maxFileSize><maxHistory>30</maxHistory><totalSizeCap>20GB</totalSizeCap></rollingPolicy><encoder><Pattern>${LOG_PATTERN}</Pattern></encoder></appender><appender name="console" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>${LOG_PATTERN}</pattern></encoder></appender><root level="info"><appender-ref ref="console"/><appender-ref ref="file"/></root><logger name="org.mybatis.spring" level="INFO"/><logger name="io.netty" level="INFO"/><logger name="com.ulisesbocchio" level="INFO"/><logger name="org.quartz" level="INFO"/></configuration>