前言:Feign是一个声明式WebService客户端,使用方法时定义一个接口并在上面添加注解即可。Feign支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持SpringMVC和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。
添加pom依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.2.6.RELEASE</version> </dependency> </dependencies>
编写yml
server: port: 8086 eureka: client: register-with-eureka: false #是否注册自己 fetch-registry: true #是否需要从Eureka Server获取服务信息,默认为true service-url: defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka
写启动类
@SpringBootApplication @EnableEurekaClient #表示这是一个客户端 @EnableFeignClients #告诉框架扫描所有使用注解 @FeignClient 定义的 feign 客户端。
写controller
package cn.bdqn.controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource;
@RestController public class UserController { @Resource private UserService userService; @GetMapping("/user/get/{id}") String getUserById(@PathVariable("id") int id){ return userService.getUserById(id); }
}
写service
package cn.bdqn.service; import cn.bdqn.config.RequestClass; import cn.bdqn.service.impl.UserServiceImpl; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Component @FeignClient(value = "CLOUD-EUREKA-SERVER") #CLOUD-EUREKA-SERVER你的微服务名 public interface UserService { @GetMapping("/user/get/{id}") RequestClass getUserById(@PathVariable("id") int id);
}
启动后访问,即会按照轮询的方式调用provider集群