feign的依赖如下
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.0.RELEASE</version> </dependency>添加@EnableFeignClients注解,注入Spring容器
package com.rui; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @author WangRui * @date 2020/10/20 16:26 */ @SpringBootApplication @EnableEurekaClient @EnableFeignClients public class ServiceConsumerApplication { public static void main(String[] args) { SpringApplication.run(ServiceConsumerApplication.class,args); } }@FeignClient(value = "service-provider"):该注解可以为该方法找到对应的微服务名称 @RequestMapping("/user/selectAll"):映射对应的微服务的访问url
package com.rui.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; /** * @author WangRui * @date 2020/10/21 15:44 */ @FeignClient(value = "service-provider") @Component public interface UserServiceFeign { @RequestMapping("/user/selectAll") String selectAll(); }添加selectAllFeign()方法用于调用UserServiceFeign接口
package com.rui.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * @author WangRui * @date 2020/10/21 14:29 */ @Service public class UserService { @Autowired private RestTemplate restTemplate; @Autowired private UserServiceFeign userServiceFeign; public String selectAll(){ return restTemplate.getForObject("http://localhost:8082/user/selectAll",String.class); } public String selectAllFeign(){ return userServiceFeign.selectAll(); } }提供@RequestMapping("/selectAllFeign")来使用feign调用微服务接口
package com.rui.controller; import com.rui.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author WangRui * @date 2020/10/21 14:32 */ @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/selectAll") public String selectAll(){ return userService.selectAll(); } @RequestMapping("/selectAllFeign") public String selectAllFeign(){ return userService.selectAllFeign(); } }通过调用http://localhost:8083/user/selectAllFeign,同样可以实现微服务应用间的调用。