0、概述
必备知识:【快速搭建Eureka注册中心】
两个服务:
- feign-eureka-hello-server:服务提供者,以下简称 hello-server
- feign-eureka-hello-client:服务调用者,以下简称 hello-client
达到的效果:
- hello-client 调用 hello-server 的函数接口,输出被调用的 hello-server 的信息。
1、创建 hello-server
和正常创建普通服务一样,但是需要向 Eureka 注册中心注册服务,让hello-client 能够找到该服务
@SpringBootApplication
@EnableDiscoveryClient //注册服务
@RestController
public class HelloServerApplication {
@Autowired
DiscoveryClient client;
@RequestMapping("/")
public String hello() {
// 获取所有的 HelloServer 服务
List<ServiceInstance> instances = client.getInstances("HelloServer");
// 随机选择一个 HelloServer 服务
ServiceInstance selectedInstance = instances
.get(new Random().nextInt(instances.size()));
// 返回选中的 HelloServer 服务实例信息
return "Hello World: " + selectedInstance.getServiceId() + ":" + selectedInstance
.getHost() + ":" + selectedInstance.getPort();
}
public static void main(String[] args) {
SpringApplication.run(HelloServerApplication.class, args);
}
}
配置文件 application.yaml
spring:
application:
name: HelloServer
server:
port: 7111
eureka:
password: password
client:
serviceUrl:
defaultZone: http://user:${eureka.password}@localhost:8761/eureka/
instance:
leaseRenewalIntervalInSeconds: 10
metadataMap:
instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}}
2、创建 hello-client
相比普通的Eureka Client, 仅仅增加了 @EnableFeignClients
注解,其他的配置没有变化。
在 Eureka Client 的基础上,引入 OpenFeign 依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
编写接口 @RequestMapping("/") 调用 HelloServer 对应的接口:
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableFeignClients
public class HelloClientApplication {
@Autowired
HelloClient client;
@RequestMapping("/")
public String hello() {
// 调用 HelloServer 对应路径的接口
return client.hello();
}
public static void main(String[] args) {
SpringApplication.run(HelloClientApplication.class, args);
}
/**
* 绑定服务 HelloServer
*/
@FeignClient("HelloServer")
interface HelloClient {
/**
* 该请求路径对应 HelloServer 中的请求路径
* @return
*/
@RequestMapping(value = "/", method = GET)
String hello();
}
}
配置文件 application.yaml
spring:
application:
name: HelloClient
server:
port: 7211
eureka:
password: password
client:
serviceUrl:
defaultZone: http://user:${eureka.password}@localhost:8761/eureka/
instance:
leaseRenewalIntervalInSeconds: 10
metadataMap:
instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}}
endpoints:
restart:
enabled: true
3、验证
访问 http://localhost:7211 , 向 hello-client 发送请求,hello-client 再向 hello-server 发送请求,调用对应的方法。
最后页面响应:Hello World: HELLOSERVER:192.168.43.17:7111
,输出 hello-server 的信息。
4、参考资料
[1] 项目地址:https://github.com/spring-cloud-samples/feign-eureka