使用openFeign替换restTemplate
1、项目结构与Spring Cloud Alibaba(一)_夕冰的博客-CSDN博客
一致,stock模块不变,order模块新增openfeign依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
2、order模块需要增加与stock服务一致的接口,此处单独增加一个包,便于区分
接口类上添加注解 @FeignClient ,name为需要调用的服务名称,path为调用的服务地址,如我在stock模块中的StockController类上增加了 @RequestMapping("stock"),如果没有,可不写path
- @FeignClient(name = "stock-server",path = "stock")
- public interface StockServer {
-
- @RequestMapping("reduce")
- String reduce();
-
- @RequestMapping("reduce1")
- String reduce1(@RequestParam("orderId") String orderId);
-
- @RequestMapping("reduce2")
- String reduce2(@RequestBody Map map);
- }
3、需要在启动类上增加启用openFeign的注解@EnableFeignClients
- @SpringBootApplication
- @EnableFeignClients
- public class OrderApplication {
- public static void main(String[] args) {
- SpringApplication.run(OrderApplication.class,args);
- }
- }
4、调用stock服务接口
- @Autowired
- StockServer stockServer;
- /**
- * openFeign调用
- * @return
- */
- @RequestMapping("add1")
- public String add1(){
- String result = stockServer.reduce();
- String result1 = stockServer.reduce1("100");
- Map map = new HashMap();
- map.put("orderId",101);
- String result2 = stockServer.reduce2(map);
- return result+"----"+result1+"----"+result2;
- }
5、启动两个服务,访问http://localhost:8080/order/add1