ribbon负载均衡,feign负载均衡,但是一个汽车不能有两个方向盘。feign声明了一个web service客户端,它是web service编程更加简单,使用feign需要创建一个接口并且对它进行注释。
之前大家用ribbon进行负载均衡,功能很强大,甚至可以自己自定义算法,feign是怎么粗来的?1.大部分的大家都可以介绍,直接调用我们的微服务来进行访问,private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT";是面向微服务的,2.大家目前都习惯面向接口编程,比如webservice接口,比如我们的dao接口,这个已经是大家的规范 2.1微服务名字获得调用地址 2.2就是通过接口+注解,获得我们的调用服务。适应社区其他程序员提出的,还是统一的面向接口编程套路。--feign
在80工程基础上新建sonsumer-feign工程,复制com包下的所用东西删除myrule,复制yml,pom依赖,修改启动类名称,feign中pom添加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
api工程pom添加,
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
api工程新建接口,
package com.atguigu.springcloud.service;
import java.util.List;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.atguigu.springcloud.entities.Dept;
@FeignClient(value = "MICROSERVICECLOUD-DEPT")
public interface DeptClientService
{
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
public Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
public boolean add(Dept dept);
}
里边的方法和微服务service里的接口一样,feign也是面向客户端的负载均衡,所以要参照80工程构建,api是公共引用部分,编辑完后maven clean ,maven install保证最新,之前面向微服务名称使用restTemplate,现在修改controller使用上边新建的feign接口,
package com.atguigu.springcloud.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.atguigu.springcloud.entities.Dept;
import com.atguigu.springcloud.service.DeptClientService;
@RestController
public class DeptController_Consumer
{
@Autowired
private DeptClientService service;
@RequestMapping(value = "/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id)
{
return this.service.get(id);
}
@RequestMapping(value = "/consumer/dept/list")
public List<Dept> list()
{
return this.service.list();
}
@RequestMapping(value = "/consumer/dept/add")
public Object add(Dept dept)
{
return this.service.add(dept);
}
}
feign工程启动类添加注解
启动7001,7002,7003三个eureka,8001,8002,8003三个微服务测试,启动feign工程,
默认轮询负载均衡算法,测试成功