Feign负载均衡(客户端)

Feign是一个声明式的Web Service客户端,比Ribbon好用,默认也是轮巡。我们只需要使用Feign创建一个接口,并用注解就好了。

案例编写:

  一:搭建Eureka服务器

  目录结构:

        

  1.1导入依赖包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springCloud</groupId>
  <artifactId>first-server</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <!-- 基于springboot -->
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

  <!-- springcloud依赖 -->
  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!-- eureka服务器依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>

</project>

  1.2编写配配置文件  在resource目录下创建application.yml文件

# 指定默认端口
server:
  port: 8761

# eureka默认把自己到服务器注册会报错,这里禁止掉

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

  1.3编写启动类

package org.wulei;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication//表示这是一个springboot应用
@EnableEurekaServer// 申明这是一个eureka服务器
public class ServerApp {

    public static void main(String[] args) {

        SpringApplication.run(ServerApp.class, args);
        //new SpringApplicationBuilder(ServerApp.class).web(true).run(args);
    }
}

  这时,浏览器访问localhost:8761会进入eureka管控台,出现这个页面就表示启动成功了,但这个时候还没有服务注册上来,下面我们继续编写服务端与客户端。

  二:编写服务提供者

   目录结构:

        

  2.1 导入依赖包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springCloud</groupId>
  <artifactId>spring_feign_police</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <!-- 基于springboot -->
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>
  <!-- springcloud -->
  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!-- eureka客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>
</project>

  2.2 编写appliaction.yml配置文件

# 设置服务名称
spring:
  application:
    name: police

# 设置eureka服务器的注册地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

  2.3 编写实体类,供接口返回json字符串使用。

public class Police {

    private Integer id;
    private String name;
    //记录访问路径用
    private String message;

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

  2.4  Controller层

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PoliceController {

    @RequestMapping(value = "/call/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Police call(@PathVariable Integer id,HttpServletRequest req) {
        Police p = new Police();
        p.setId(id);
        p.setName("吴磊");
        p.setMessage(req.getRequestURL().toString());
        return p;
    }

    @RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name){
        return "hello"+name;
    }
}

  2.5 编写启动类

import java.util.Scanner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient//开启eureka服务
public class PoliceServer {

    public static void main(String[] args) {
        //new SpringApplicationBuilder(PoliceServer.class).web(true).run(args);
        //1. 启动main方法后,在控制台输入端口号.
        Scanner scan = new Scanner(System.in);
        String port = scan.nextLine();
        //以输入的端口号启动
        new SpringApplicationBuilder(PoliceServer.class)
                .properties("server.port="+port).run(args);
        //2. 启动2次,分别以8080, 8081启动,浏览器访问测试一下。
    }
}

  分别访问8080和8081端口进行测试, 刷新eureka管控台,这里看到我们的服务已经注册上去了。

三:编写服务调用者

  目录结构:

        

  3.1 导入依赖包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.crazyit.cloud</groupId>
    <artifactId>spring_feign_person</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!-- 基于springboot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>
    <!-- springCloud -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!-- eureka客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
         <!-- feign客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>

</project>

  3.2 编写application.yml配置信息

# 指定端口
server:
  port: 9000

# 服务名称
spring:
  application:
    name: invoker

# eureka服务器注册地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

  3.3 我们要调用服务提供者的 host:port/call/{ id } 接口返回实体类信息,所以把之前的实体复制过来,减少系统耦合度。

public class Police {

    private Integer id;
    private String name;
    private String message;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

  3.4 用feign注解来远程调用

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;
//指定服务提供者的服务名
@FeignClient("police")
public interface HelloClient {
    //翻译服务提供者的地址
    @RequestMapping(method = RequestMethod.GET, value="/hello/{name}")
    String hello(@PathVariable("name") String name);

    //翻译服务提供者的地址
    @RequestMapping(method = RequestMethod.GET, value="/call/{id}")
    Police getPolice(@PathVariable("id") Integer id);
}

  3.5 编写controller

package org.wulei;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
    //把刚才的feign注解类依赖过来
    @Autowired
    private HelloClient helloClient;

    @RequestMapping(method = RequestMethod.GET, value="/router")
    public String router() {
        String result = helloClient.hello("angus");
        return result;
    }
    @RequestMapping(method = RequestMethod.GET, value="/police",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public Police getPolice() {
        Police p = helloClient.getPolice(1);
        return p;
    }

}

  3.6 编写主函数入口

@SpringBootApplication
@EnableEurekaClient//开启eureka
@EnableFeignClients//开启feign
public class ServerMain {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ServerMain.class).web(true).run(args);
    }

}

  3.7 测试 我们调用消费者的接口,实际是用feign远程调用的服务提供者。刷新eureka管控台,可以看到消费者注册成功了。

原文地址:https://www.cnblogs.com/wlwl/p/9475135.html

时间: 2024-08-30 18:08:56

Feign负载均衡(客户端)的相关文章

SpringCloud学习(5)——Feign负载均衡

Feign概述 Feign是声明式的Web服务客户端, 使得编写Web服务客户端变的非常容易, 只需要创建一个接口, 然后在上面添加注解即可. Feign旨在使编写Java Http客户端变的更容易. 在使用Ribbon+RestTemplate时, 利用RestTemplate对http请求的封装处理, 形成了一套模板化的调用方法.但是在实际开发中, 由于对服务依赖的调用可能不止一处, 往往一个接口会被多出调用, 所以通常都会针对每个微服务自行封装一些客户端类来包装这些以来服务的调用.所以Fe

(05)SpringCloud实战之Feign负载均衡

一.概述 1.官方解释 Feign是一个声明式WebService客户端.使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解.Feign也支持可拔插式的编码器和解码器.Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters.Feign可以与Eureka和Ribbon组合使用以支持负载均衡. 通俗的说,Feign是一个声明式的Web

SpringCloud学习系列-Feign负载均衡(2)

Feign使用步骤 1.参考microservicecloud-consumer-dept-80   新建microservicecloud-consumer-dept-feign 修改主启动类名字DeptConsumer80_Feign_App 2.microservicecloud-consumer-dept-feign工程pom.xml修改,主要添加对feign的支持 <dependency> <groupId>org.springframework.cloud</gr

Spring Cloud Feign服务通信与负载均衡机制

首先要知道一点Feign的负载均衡是Ribbon来实现的. Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单.Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数.格式.地址等信息.而Feign则会完全代理HTTP请求,我们只需要像调用方法一样调用它就可以完成服务请求及相关处理.Feign整合了Ribbon和Hystrix(Hystrix熔断保护机制),可以让我们不再需要显式地使用这两个组件. Fe

Spring Cloud(十四):Ribbon实现客户端负载均衡及其实现原理介绍

年后到现在一直很忙,都没什么时间记录东西了,其实之前工作中积累了很多知识点,一直都堆在备忘录里,只是因为近几个月经历了一些事情,没有太多的经历来写了,但是一些重要的东西,我还是希望能坚持记录下来.正好最近公司用到了一些本篇文章的知识点,所以就抽空记录一下. 本文代码github地址:https://github.com/shaweiwei/RibbonTest/tree/master 简介 ribbon 是一个客户端负载均衡器,它和nginx的负载均衡相比,区别是一个是客户端负载均衡,一个是服务

浅谈SpringCloud (三) Ribbon负载均衡

什么是负载均衡 当一台服务器的单位时间内的访问量越大时,服务器压力就越大,大到超过自身承受能力时,服务器就会崩溃.为了避免服务器崩溃,让用户有更好的体验,我们通过负载均衡的方式来分担服务器压力. 我们可以建立很多很多服务器,组成一个服务器集群,当用户访问网站时,先访问一个中间服务器,在让这个中间服务器在服务器集群中选择一个压力较小的服务器,然后将该访问请求引入该服务器.如此以来,用户的每次访问,都会保证服务器集群中的每个服务器压力趋于平衡,分担了服务器压力,避免了服务器崩溃的情况. Ribbon

SpringCloud微服务负载均衡与网关

1.使用ribbon实现负载均衡ribbon是一个负载均衡客户端 类似nginx反向代理,可以很好的控制htt和tcp的一些行为.Feign默认集成了ribbon. 启动两个会员服务工程,端口号分别为8762.8763,订单服务使用负载均衡策略轮训到会员服务接口. 在上一篇SpringCloud微服务基础上修改Service_Menber项目代码区分端口项目 package com.zhang.controller; import org.springframework.beans.factor

【Spring Cloud学习之三】负载均衡

环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 Spring Cloud 1.2 主流的负载均衡技术有nginx.LVS.HAproxy.F5,Spring Cloud使用ribbon. 一.ribbonribbon是一个负载均衡客户端 类似nginx反向代理,可以很好的控制http和tcp的一些行为.Feign默认集成了ribbon. 二.案例 1.修改上一篇的service-member的controller package com.wjy.controll

Nginx入门简介和反向代理、负载均衡、动静分离理解

场景 Nginx简介 Nginx ("engine x")是一个高性能的 HTTP 和反向代理服务器 特点是占有内存少,并发能力强,事实上 nginx 的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用 nginx网站用户有:百度.京东.新浪.网易.腾讯.淘宝等. Nginx可以作为静态页面的 web 服务器,同时还支持 CGI 协议的动态语言,比如 perl . php等.但是不支持 java . Java 程序只能通过与 tomcat 配合完成. Nginx 专为性能优化而