Feign负载均衡
feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。SpringCloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端,
只需要创建一个接口,然后添加注解即可!
1.微服务名字【ribbon]
2.接口和注解【feign ]
feign 能干什么
在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它(类似于以前Dao接口上标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解即可。)
包结构
第一步、写service
- springcloud-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> queryALL();
@GetMapping("/dept/add")
public boolean addDept(Dept dept);
}
第二步copy项目 名字为springcloud-sonsumer-dept-feign,添加依赖
- springcloud-api和本项目都添加feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
第三步、controller层的变化
@RestController
public class DeptConsumerController {
@Autowired
private DeptClientService service=null;
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept){
return this.service.addDept(dept);
}
@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.queryALL();
}
}
80-feign controller对比
第四步、主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.tian.springcloud"})
//@ComponentScan("com.tian")
public class FeignDeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(FeignDeptConsumer_80.class,args);
}
}
开启7001 8001 8002 feign
测试访问 http://localhost/consumer/dept/list