服务注册中心搭建好之后需要将服务注册上去,这样客户端就可以调用该服务了。下面简单的通过一个简单的例子说明怎么将服务注册到服务注册中心中。
(1)pom.xml中增加对eurekaClient的依赖
<!-- 添加Eureka的依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
(2)项目启动类上增加注解
@SpringBootApplication
@EnableDiscoveryClient//通过注解@EnableDiscoveryClient激活eureka的DiscoveryClient的实现(自动化配置,创建DiscoveryClient对EurekaDiscoveryClient的实现)
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
(3)yml配置文件中增加配置,指明项目名
spring:
application:
name: microservice-provider-user # 项目名称尽量用小写
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ # 指定注册中心的地址
(4)发布一个服务出去
/**
* 作用:
* ① 测试服务实例的相关内容
* ② 为后来的服务做提供
* @author liugd
*/
@RestController//指明为一个controller
public class UserController {
@Autowired
private DiscoveryClient discoveryClient;
/**
* 本地服务实例的信息
* @return
*/
@GetMapping("/instance-info")
public ServiceInstance showInfo() {
ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
return localServiceInstance;
}
}