Eureka注册中心通用写法和配置

  • 下面简单介绍下 Eureka 注册中心的通用写法

  • 新建个空项目,pom 中加入如下依赖

xml 复制代码
<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
java 复制代码
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${eureka.security.enabled:false}")
    private boolean securityEnabled;

    @Override
    protected 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 包下,新建启动类
java 复制代码
@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:off
        log.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
yml 复制代码
spring:
  application:
     name: eureka-registry
  # 配置认证用户名和密码,不配置系统会随机生成
  security:
    user:
      name: user	#认证用户名
      password: 123456 #认证密码
server:
  port: 8081
    
eureka:
  server:
    #关闭自我保护模式
    enableSelfPreservation: false
    #主动失效时间,默认60*1000
    evictionIntervalTimerInMs: 5000
    #禁用readOnlyCacheMap
    useReadOnlyResponseCache: false
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      #defaultZone: http://localhost:8081/eureka/  #未开启认证时url
      defaultZone: http://user:123456@localhost:8081/eureka/ #开启认证时url


management:
  endpoints:
    web:
      exposure:
        include: "*" #["configprops", "env", "health", "info", "jhimetrics", "logfile", "loggers", "threaddump"]
  endpoint:
    health:
      show-details: always #when_authorized
    env:
      enabled: false
    mappings:
      enabled: false
    configprops:
      enabled: false
    heapdump:
      enabled: false
    loggers:
      enabled: false
    conditions:
      enabled: false
    beans:
      enabled: false
  metrics:
    enable:
      http: true
      jvm: true
      logback: true
      process: true
      system: true
    distribution:
      percentiles-histogram:
        all: true
      percentiles:
        all: 0, 0.5, 0.75, 0.95, 0.99, 1.0
  • logback-spring.xml
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>
相关推荐
寻星探路5 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
曹牧7 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
爬山算法8 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7258 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎8 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄8 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
忆~遂愿9 小时前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能
小韩学长yyds9 小时前
Java序列化避坑指南:明确这4种场景,再也不盲目实现Serializable
java·序列化
仟濹9 小时前
【Java基础】多态 | 打卡day2
java·开发语言