Spring Cloud (二)、向注册中心注册服务提供者

        在向注册中心注册服务提供者时必须先搭建好服务注册中心,可参考Spring Cloud (一)、搭建服务注册中心。搭建好服务注册中心,现在我们开始向服务注册中心中注册服务提供者。

一、创建项目

创建项目的过程和搭建服务注册中心新建项目基本一致,只需改动以下一个小小的地方:

将这里勾选成Eureka Discovery Client,不需要勾选Eureka Server。其他步骤都一样!!!

二、配置服务提供者

1、在启动主类上通过加上@EnableDiscoveryClient注解,激活Eureka中的DiscoveryClient实现。

@EnableDiscoveryClient
@SpringBootApplication
public class SpringBootHelloApplication {

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

}

这里要说明一下@EnableDiscoveryClient和@EnableEurekaClient的区别?

        在Spring Cloud中discovery service有许多种实现(如:eureka、consul、zookeeper...)。

        @EnableDiscoveryClient基于spring-cloud-commons;而@EnableEurekaClient基于spring-cloud-netflix。

        @EnableEurekaClient有@EnableDiscoveryClient的功能。

         使用场景:@EnableEurekaClient只能是在服务采用eureka作为注册中心的时候使用,场景比较单一;

                           @EnableDiscoveryClient在使用其他注册中心都是可以使用的,使用范围较广。

2、在application.properties配置文件中来指定服务名和服务注册中心的地址(这个地址就是在搭建服务注册中心中所配置的地址):

#为服务命名
spring.application.name=hello-service
#指定服务注册中心地址
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/

3、分别启动服务注册中心和服务提供者,在hello-service服务控制台中,Tomcat启动之后com.netflix.discovery.DiscoveryClient 对象打印了该服务的注册信息,表示服务注册成功。

o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
.s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8080
c.e.s.SpringBootHelloApplication         : Started SpringBootHelloApplication in 4.359 seconds (JVM running for 5.094)
com.netflix.discovery.DiscoveryClient    : DiscoveryClient_HELLO-SERVICE/DESKTOP-LTR8285:hello-service - registration status: 204

    而此时在服务注册中心的控制台中,我们可以看到类似下面的输出,名为hello-service的服务被注册成功了。

c.n.e.registry.AbstractInstanceRegistry  : Registered instance HELLO-SERVICE/DESKTOP-LTR8285:hello-service with status UP (replication=false) 

 我们也可以通过访问Eureka的信息面板,在Instances currently registered with Eureka一栏中看到服务的注册信息。

猜你喜欢

转载自blog.csdn.net/hdn_kb/article/details/92143396
今日推荐