上一篇文章我們介紹了eureka服務注冊中心的搭建,這篇文章介紹一下如何使用eureka服務注冊中心,搭建一個簡單的服務端注冊服務,客戶端去調用服務使用的案例。
案例中有三個角色:服務注冊中心、服務提供者、服務消費者,其中服務注冊中心就是我們上一篇的eureka單機版啟動既可,流程是首先啟動注冊中心,服務提供者生產(chǎn)服務并注冊到服務中心中,消費者從服務中心中獲取服務并執(zhí)行。
服務提供
我們假設服務提供者有一個hello方法,可以根據(jù)傳入的參數(shù),提供輸出“hello xxx,this is first messge”的服務
1、pom包配置
創(chuàng)建一個springboot項目,pom.xml中添加如下配置:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>復制代碼
2、配置文件
application.properties配置如下:
spring.application.name=spring-cloud-producer
server.port=9000
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/復制代碼
參數(shù)在上一篇都已經(jīng)解釋過,這里不多說。
3、啟動類
啟動類中添加@EnableDiscoveryClient注解
@SpringBootApplication
@EnableDiscoveryClient
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
}復制代碼
4、controller
提供hello服務
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index(@RequestParam String name) {
return "hello "+name+",this is first messge";
}
}復制代碼
添加@EnableDiscoveryClient注解后,項目就具有了服務注冊的功能。啟動工程后,就可以在注冊中心的頁面看到SPRING-CLOUD-PRODUCER服務。

image.png
到此服務提供者配置就完成了。