基于spring boot 2.x cloud服务注册与发现

创建服务注册中心

创建一个基于Spring boot 2.x的工程,命名为eureka-server,相比spring boot1
.x系列,eureka-server的依赖有变化,spring-cloud的版本也需要修改成Finchley.RC1版本,pom.xml如下:


    org.springframework.boot
    spring-boot-starter-parent
    2.0.1.RELEASE
    



    UTF-8
    UTF-8
    1.8



    
        org.springframework.boot
        spring-boot-starter
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
    

    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-server
    

    
        org.springframework.cloud
        spring-cloud-starter-config
    



    
        
            org.springframework.cloud
            spring-cloud-dependencies
            Finchley.RC1
            pom
            import
        
    

通过@EnableEurekaServer注解启动一个服务注册中心提供给其他应用进行对话

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

并在application.yml配置文件中增加如下信息:

spring:
  application:
    name: eureka-server
server:
  port: 1001
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false

启动工程后,访问:http://localhost:1001/,可以看到下面的页面,其中还没有任何服务

1.png

创建服务注册发现端

创建一个新的springboot工程,命名为eureka-client,作为提供服务的客户端,并向服务注册中心注册自己,pom.xml如下


    UTF-8
    UTF-8
    1.8



    
        org.springframework.boot
        spring-boot-starter
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
    

    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-server
    



    
        
            org.springframework.cloud
            spring-cloud-dependencies
            Finchley.RC1
            pom
            import
        
    

并实现一个接口,通过DiscoveryClient对象打印客户端名称和端口:

@RestController
public class TestController {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String port;

    @GetMapping("/disc")
    public String dc() {
        return "Services: " + discoveryClient.getServices() + ":" + port;
    }
}

启动类这里通过@EnableDiscoveryClient进行注解启动一个服务提供端,并激活DiscoveryClient

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {

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

application.yml需要配置注册中心地址和服务名称:

spring:
  application:
    name: eureka-client
server:
  port: 2001
eureka:
  instance:
    hostname: localhost
    prefer-ip-address: true
    instance-id: ${eureka.instance.hostname}:${spring.application.name}:${server.port}
  client:
    serviceUrl:
      defaultZone: http://localhost:1001/eureka/ 

启动工程,刷新 http://localhost:1001/ 页面会多出刚才我们启动的 eureka-client 服务,访问 http://localhost:2001/disc 接口,会打印Services: [eureka-client]:2001信息。

你可能感兴趣的:(基于spring boot 2.x cloud服务注册与发现)