Feign的目标
Feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
引入Feign
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
|
在启动类添加@EnableFeignClients注解支持
1 2 3 4 5 6 7 8 9 10 11
| @SpringBootApplication @EnableDiscoveryClient
@EnableFeignClients public class FeignApplication { public static void main( String[] args ) { SpringApplication.run(FeignApplication.class,args); } }
|
建立Client接口,并在接口中定义需调用的服务方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.cxy.test.Feign;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name="mybatis") @RequestMapping("/api") public interface TestClient {
@GetMapping("/getusers") List<User> getUsers();
}
|
说明:
- name=”CLIENT”,这里的”CLIENT”是注册到Eureka 中的要调用的应用名
- @GetMapping(“/getMsg”) 这里的“getMsg”是要调用的应用里的相应的方法(这里需注意,如果CLIENT服务下面的访问路径是 /list/getMsg ,则这里也要写”/list/getMsg”)。
写一个Controller尝试连接
1 2 3 4 5 6 7 8 9 10 11 12 13
| @RestController public class TestController { private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired private TestClient testClient;
@GetMapping("/gettestusers") public List<User> getTestUsers(){ logger.info("gettestusers"); return testClient.getUsers(); } }
|
启动成功

示例代码-github
以下为所有本次的文件,上面2图为项目springboot-mybatis的,下面3图为springboot-feign项目

示例代码-github