上文在Eureka服务调用方示例的pom文件中加入Feign的Maven依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
定义Feign接口类:
@FeignClient(name = "MYPROVIDER") public interface IBizApi { @RequestMapping("/sayHello") public String sayHello(@RequestParam("name") String name); }
然后在主类上标注@EnableFeignClients。
@SpringBootApplication @EnableFeignClients @EnableEurekaClient @Slf4j @RestController public class FeignClientApplication { @Autowired private IBizApi bizApi; @RequestMapping("/sayHello") public String sayHello(){ return bizApi.sayHello("haha"); } public static void main(String[] args) { SpringApplication.run(FeignClientApplication.class, args); } }
这样就能很方便地把一个HTTP的请求方式转换为编码友好的Java接口形式。