SpringCloud Feign的使用代码实例
1.官方文档
https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.2.RELEASE/reference/html/
2.添加依赖
org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-openfeign
3.添加启动类注解
importorg.mybatis.spring.annotation.MapperScan;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
//@MapperScan("cn.ytheng.order_service")
@EnableFeignClients
publicclassOrderServiceApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(OrderServiceApplication.class,args);
}
}
4.添加Feign接口
importorg.springframework.cloud.openfeign.FeignClient;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestParam;
/**
*
*商品服务客户端
*product-service:调用服务名称,即spring.application.name
*
*/
@FeignClient(name="product-service")
publicinterfaceProductClient{
@GetMapping("/api/v1/product/find")
StringgetById(@RequestParam("id")intid);
}
5.添加Controller
importcn.theng.order_service.service.ProductClient;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/order")
publicclassProductOrderController{
@Autowired
privateProductClientproductClient;
@PostMapping("/test2")
publicObjecttest2(@RequestParam("product_id")intproductId){
Stringproduct=productClient.getById(productId);
return"success";
}
}
6.添加application.yml配置
server: port:8781 eureka: client: serviceUrl: defaultZone:http://localhost:8761/eureka/ spring: application: name:order-service #设置调用服务超时时间 #product-service为服务名称,也可以设置为默认值default feign: client: config: product-service: connectTimeout:5000 readTimeout:11000
7.访问地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。