通过注解@EnableEurekaClient 表明自己是一个eurekaclient,也即服务的提供者。
启动类代码如下:
1 package com.cloud.microservice.demo;
2
3 import org.springframework.boot.SpringApplication;
4 import org.springframework.boot.autoconfigure.SpringBootApplication;
5 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
6 import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
7 import org.springframework.context.annotation.ComponentScan;
8
9 @SpringBootApplication
10 @EnableDiscoveryClient
11 @EnableEurekaClient
12 @ComponentScan("com.cloud.microservice.demo")
13 public class DemoProviderApplication {
14
15 public static void main(String[] args) {
16 SpringApplication.run(DemoProviderApplication.class, args);
17 }
18 }
为了把启动类和接口分离,我这里新建了一个provider包,把Rest接口UserProvider.java放在该路径下,工程结构如下:
UserProvider.java代码如下:
1 package com.cloud.microservice.demo.provider;
2
3 import org.springframework.cloud.netflix.feign.FeignClient;
4 import org.springframework.web.bind.annotation.RequestMapping;
5 import org.springframework.web.bind.annotation.RequestMethod;
6 import org.springframework.web.bind.annotation.RequestParam;
7 import org.springframework.web.bind.annotation.RestController;
8
9 @FeignClient(name = "ms-demo-provider")
10 @RestController
11 @RequestMapping("/demo/user")
12 public class UserProvider {
13
14 @RequestMapping(value="/1.0/findAll",method= RequestMethod.GET)
15 public String findAll(@RequestParam String name)
16 {
17 return "hello,this is "+name;
18 }
19 }
配置文件application.yml如下:registerWithEureka表示是否注册自身到eureka服务器,由于当前该应用就是eureka服务,为了在Eureka服务上能看到注册信息,这里设为true;fetchRegistry表示是否从eureka服务器获取注册信息。
1 server:
2 port: 8090
3
4 eureka:
5 instance:
6 hostname: localhost
7 client:
8 registerWithEureka: true
9 fetchRegistry: false
10 serviceUrl:
11 defaultZone: http://${eureka.instance.hostname}:9090/eureka/
12
13 spring:
14 application:
15 name: ms-demo-provider
启动工程,打开http://localhost:9090 ,即eureka server 的网址,这时会发现一个服务已经注册在服务中了,服务名为MS-DEMO-PROVIDER ,端口为8090。
在浏览器地址栏中输入http://localhost:8090/demo/user/1.0/findAll?name=helloworld,如下图,说明服务接口访问正常。