微服务学习SpringCloud之Feign实现负载均衡

写在前面:后续的文章都是基于第一篇文章进行更新,我是按照SpringCloud学习顺序进行文章编写,因为项目只有一个项目,需要了解SpringCloud前面skill的可以看一下前面SpringCloud体系。

上面一篇文章中介绍到使用Ribbon实现了负载均衡策略。SpringCloud实现负载均衡的方式还有一种通过Fegin的方式。

具体实现如下:

新建一个Fegin模块,这个模块和之前的消费端模块一样,在这个模块之上进行更改

在之前的common模块增加依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

同时这个模块也需要增加对Fegin支持的依赖,和上面一样

在common模块添加Fegin接口支持

package com.gysoft.bean.fegin;


import com.gysoft.bean.Dept;
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 java.util.List;

/**
 * @Description
 * @Author DJZ-WWS
 * @Date 2019/5/9 16:04
 */
@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);
}
在fegin消费模块增加新的Controller
package com.gysoft.controller;

/**
 * @Description
 * @Author DJZ-WWS
 * @Date 2019/5/9 16:09
 */

import java.util.List;

import com.gysoft.bean.Dept;
import com.gysoft.bean.fegin.DeptClientService;
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;



@RestController
public class DeptController_Feign
{
    @Autowired
    private DeptClientService service = null;

    @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);
    }
}

在启动类上增加 注解@EnableFeignClients,启用Fegin功能。

先编译一下common 命令 mvn clean insatll

测试

启动Eureka集群。启动三个服务,启动fegin消费者

访问地址:

结果:

[{"deptno":1,"dname":"开发部","db_source":"clouddb02"},
{"deptno":2,"dname":"人事部","db_source":"clouddb02"},
{"deptno":3,"dname":"财务部","db_source":"clouddb02"},
{"deptno":4,"dname":"市场部","db_source":"clouddb02"},
{"deptno":5,"dname":"运维部","db_source":"clouddb02"}]

多访问几次,发现每次返回的数据库都不一样,和Ribbon实现了同样效果。

就这样实现了Fegin的负载均衡,和Ribbon不一样的是它通过接口的方式,Ribbon通过和Eureka整合去Eureka里面发现服务地址,自身在做一次选择。

经验分享 程序员 微信小程序 职场和发展