1.概述
Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。
2.入门案例
改造lucky-service-consumer模块
(1)导入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
(2)
@EnableFeignClients
package lucky.service; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringCloudApplication @EnableFeignClients // 开启feign客户端 public class LuckyServiceConsumerApplication { public static void main(String[] args) { SpringApplication.run(LuckyServiceConsumerApplication.class, args); } }
(3)
package lucky.service.client; import lucky.service.domain.Users; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * value = "SERVICE-PROVIDER" 这里的"SERVICE-PROVIDER"是Eureka 注册中心中的要调用的服务应用名 * @RequestMapping(path = "/users/queryUsersById") 这里的“getMsg”是要调用的服务应用里的相应的方法 * 注意:如果SERVICE-PROVIDER服务下面的访问路径是 /users/queryUsersById ,则这里也要写"/users/queryUsersById) * public Users queryUserById(@RequestParam("id") Integer id); 方法完全复制UserController中的方法,方法名可以修改(即方法名可以自定义) */ @FeignClient(value = "SERVICE-PROVIDER") public interface UserClient { @RequestMapping(path = "/users/queryUsersById") public Users queryUserById(@RequestParam("id") Integer id); }
注意:
* value = "SERVICE-PROVIDER" 这里的"SERVICE-PROVIDER"是已在Eureka 注册中心注册的要调用的服务应用名
* @RequestMapping(path = "/users/queryUsersById") 这里的“getMsg”是要调用的服务应用里的相应的方法
* 注意:如果SERVICE-PROVIDER服务下面的访问路径是 /users/queryUsersById ,则这里也要写"/users/queryUsersById)
* public Users queryUserById(@RequestParam("id") Integer id); 方法完全复制UserController中的方法,方法名可以修改(即方法名可以自定义)
(4)UserController.java
修改UserController,调用UserClient接口:
package lucky.service.controller; import lucky.service.client.UserClient; import lucky.service.domain.Users; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.util.List; /** * 逻辑分析:浏览器中输入http://localhost:8080/consumer/user/queryUsersById?id=2 * url中:/consumer/user 对应类上注解的路径 * url中:/queryUsersById 对应方法路径 * 调用userClient向服务端发请求 */ @Controller @RequestMapping(path = "/consumer/user") public class UserController { @Autowired private UserClient userClient; @RequestMapping(path = "/queryUsersById") @ResponseBody public Users queryUserById(@RequestParam("id") Integer id){ Users users = this.userClient.queryUserById(id); return users; } }
(5)测试结果