快捷搜索: 王者荣耀 脱发

SpringCloud注册中心Eureka

SpringCloud Eureka是SpringCloud Netflix 微服务套件的一部分,主要负责完成微服务架构中的服务治理功能。服务治理可以说是微服务架构中最为核心和基础的模块,它主要用来实现各个微服务实例的自动化注册和发现。

一、创建module之配置服务项目zx-eureka

主要依赖引入

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

spring-cloud-starter-netflix-eureka-server 是注册中心eureka服务端需要引入的重要依赖 spring-boot-starter-security 对注册中心eureka设置账号密码需要

aplication.yml主要配置

server:
  port: 8002

logging:
  config: classpath:logback.xml

bootstrap.yml

spring:
  security:
    user:
      name: zxdemo
      password: zxdemopwd
  application:
    name: zx-eureka

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    healthcheck:
      enabled: true
    service-url:
      defaultZone: http://zxdemo:zxdemopwd@127.0.0.1:8002/eureka/
  instance:
    prefer-ip-address: true
    ip-address: 127.0.0.1
  server:
    enable-self-preservation: false

配置主要说明

fetch-registry: 检索服务选项,当设置为True(默认值)时,会进行服务检索,注册中心不负责检索服务。

register-with-eureka: 服务注册中心也会将自己作为客户端来尝试注册自己,为true(默认)时自动生效

eureka.client.service-url.defaultZone是一个默认的注册中心地址。配置该选项后,可以在服务中心进行注册。

一般情况下,当我们设置服务为注册中心时,需要关闭eureka.client.fetch-registry与eureka.client.register-with-eureka,在做注册中心集群的时候,register-with-eureka必须打开,因为需要进行相互注册,不然副本无法可用。

本示例采用非集群模式,所以register-with-eureka和fetch-registry都设置为false

创建启动类

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }

    @EnableWebSecurity
    static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().ignoringAntMatchers("/**").and().authorizeRequests().anyRequest()
                    .authenticated().and().httpBasic();
        }
    }
}

@EnableWebMvcSecurity 注解开启Spring Security的功能 @EnableEurekaServer 注解开启Eureka Server

运行项目

访问:

欢迎访问博主的独立站:

经验分享 程序员 微信小程序 职场和发展