Openfeign

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": "其他部门"
        }
    ]
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值