1.pom文件
在pom文件中引入feign坐标
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
fegin服务需要注册在eureka上,才能调用eureka上的其他服务
2.配置文件
配置相应的eureka参数,将服务注册的eureka server上。
eureka:
instance:
prefer-ip-address: true
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
3.添加注解
在启动类上添加相应的注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.example.feignclient1"}) ⇽--- feign接口所在的包目录,basePackages属性的值是一个数组,可以配置多个feign目录。开启feign的客户端
public class FeignClient1Application {
public static void main(String[] args) {
SpringApplication.run(FeignClient1Application.class, args);
}
}
4.feign接口示例
feign接口
@FeignClient(value = "EUREKA-CLIENT-1")
public interface DeptFeignClient {
@RequestMapping(method = RequestMethod.GET, path = "/dept/getListById", consumes = "application/json")
RestDto<List<IdNameDto>> getDeptList(@RequestParam("id")String id);
@RequestMapping(method = RequestMethod.POST, path = "/dept/queryByCriteria")
RestDto<List<IdNameDto>> query(@RequestBody Criteria criteria);
}
- @FeignClient(value = “EUREKA-CLIENT-1”) :此接口是一个feign接口,value值为被调用服务在eureka服务上的注册id,也就是该服务的服务名称。
- feign自动集成了ribbon,分布式服务默认使用轮询的策略。
5.代码示例
@Autowired
private DeptFeignClient deptFeignClient;
public List<IdNameDto> getOrgList(String id) throws Exception {
RestDto<List<IdNameDto>> deptList = deptFeignClient.getDeptList(id);
if (deptList.getResult().equals(0)){
return deptList.getData();
} else {
throw new Exception("feign调用异常");
}
}
结果展示
{
"code": "200",
"result": 0,
"msg": "操作成功",
"data": [
{
"id": "200",
"name": "其他部门"
}
]
}