版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tang86100/article/details/78898765
RestTemplate是不是很简单粗暴呢?还有更粗暴的,那就是Feign,很多人都用过Dubbo,Feign的用法跟他类似。
我们复用userService那个module去调用productService微服务中的getProduct接口,引入Feign的依赖包:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>在userService中创建一个接口,接口中要创建一个和微服务中要调用方法同名的方法,如下:
package com.tzy.userService; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(value = "service-product") public interface GetProductInterface { @RequestMapping(value = "/getProduct") String getProduct(); }@FeignClient里的value指向要调用的微服务
@RequestMapping指向要远程调用的方法
另外要在启动程序Main.java里的类上加上@EnableFeignClients,表示为服务中要使用FeignClient。
package com.tzy; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @SpringBootApplication @EnableEurekaClient @EnableFeignClients public class Main { public static void main(String[] args){ SpringApplication.run(Main.class,args); } }写一个Controller直接调这个接口测一下
package com.tzy.userService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GetProductController { @Autowired GetProductInterface getProductInterface; @Autowired GetProductService getProductService; @RequestMapping(value = "/getGoods") public String getGoods(){ return getProductInterface.getProduct(); } }
结果可以得到正确的返回值。