Feign负载均衡
作者:互联网
公共模块
导入依赖
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
编写FeignClient
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
,添加Eureka中服务提供方的名称,再通过url访问时即可调用该服务中对应的api接口
//@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
@GetMapping("/dept/get/{id}")
public Dept queryById(@PathVariable("id") Long id);
@GetMapping("/dept/list")
public List<Dept> queryll();
@PostMapping("/dept/add")
public boolean addDept(Dept dept);
}
服务消费方
导入依赖
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<!--eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
编写配置文件
# Eureka配置
eureka:
client:
register-with-eureka: false #不向Eureka注册自己
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
开启相关功能
// Ribbon和Eureka整合以后,客户端可以直接调用,不用关心ip地址和端口号
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.song.springcloud"})
//@ComponentScan("com.song.springcloud")
// 在微服务启动的时候就能去加载我们自定义的Ribbon类
public class FeignDeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(FeignDeptConsumer_80.class, args);
}
}
编写Controller
Controller调用公共模块的接口
@RestController
public class DeptConsumerController {
// 理解:消费者,不应该有service层
// RestTemplate ... 供我们直接调用就可以了!注册到Spring中
// (url,实体:map,Class<T> responseType)
@Autowired
private RestTemplate restTemplate;//提供多种便捷访问远程http服务的方法,简单restful服务模板
@Autowired
private DeptClientService service = null;
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept) {
return this.service.addDept(dept);
}
// http://127.0.0.1:8001/dept/list
@RequestMapping("/consumer/dept/get/{id}")
public Dept get(@PathVariable("id")Long id) {
return this.service.queryById(id);
}
@RequestMapping("/consumer/dept/list")
public List<Dept> list() {
return this.service.queryll();
}
}
标签:Feign,service,负载,public,dept,均衡,eureka,id,cloud 来源: https://www.cnblogs.com/singob/p/16692785.html