摘要:Feign是一个声明式、模板化的HTTP客户端调用组件,它可以像调用本地方法一样调用远程服务。
创建一个新的服务:microservice-provider-user,在microservice-provider-user中使用Feign调用microservice-provider-org发布的服务/org/query/{id}。
1、以microservice-provider-org作为模板创建一个springboot服务:microservice-provider-user,在maven配置中增加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
2、修改application.yml的服务名和端口号:
server:
port: 9002
spring:
application:
name: user-service #服务名,将注册到eureka注册中心
eureka:
instance:
statusPageUrlPath: ${management.context-path}/info
healthCheckUrlPath: ${management.context-path}/health
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ #注册地址,eureka服务地址
3、启动类增加Feign注解:@EnableFeignClients。
4、使用Feign调用microservice-provider-org发布的服务:
package com.netsframe.user.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient("org-service")
public interface UserService {
@RequestMapping("/org/query/{id}")
public String queryOrg(@PathVariable("id") String id);
}
@FeignClient:发现microservice-provider-org发布到注册中的服务。
5、在controller调用UserService:
package com.netsframe.user.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netsframe.user.service.UserService;
@RestController()
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/user/query/{id}")
public String query(@PathVariable("id") String id) {
String org = userService.queryOrg(id);
return "小陈所属组织:" + org;
}
}
6、依次启动microservice-register-eureka、microservice-provider-org、microservice-provider-user,访问http://localhost:8761/,显示如下界面:
从上图看出,新的服务USER-SERVICE已经发布到注册中心了,访问user-service中的请求:http://localhost:9002/user/query/1,返回:
从上面返回结果看,在microservice-provider-user中通过feign调用microservice-provider-org发布的服务成功。
至此,本文介绍的通过Feign调用服务结束。