1. 程式人生 > >SpringCloud微服務負載均衡與閘道器

SpringCloud微服務負載均衡與閘道器

1、使用ribbon實現負載均衡
ribbon是一個負載均衡客戶端 類似nginx反向代理,可以很好的控制htt和tcp的一些行為。Feign預設集成了ribbon。

啟動兩個會員服務工程,埠號分別為8762、8763,訂單服務使用負載均衡策略輪訓到會員服務介面。

 

在上一篇SpringCloud微服務基礎上修改Service_Menber專案程式碼區分埠專案

package com.zhang.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class MemberController { @Value("${server.port}") private String serverPort; @RequestMapping("/getMemberAll") public List<String> getUserList() { List
<String> listUser = new ArrayList<String>(); listUser.add("zhangsan"); listUser.add("lisi"); listUser.add("zhang"); listUser.add("埠號:"+serverPort); return listUser; } }

將Service_Menber專案複製一份,名為Service_Menber負載均衡,埠改為8763。分別啟動Eureka、Service_Menber、Service_Menber負載均衡、Service_Order,然後訪問http://127.0.0.1:8764/getOrderUserAll,第一次出現8762 第二次出現8763。依次輪詢,說明負載均衡配置成功。

 2、路由閘道器(zuul)

Zuul的主要功能是路由轉發和過濾器。路由功能是微服務的一部分,比如/api/user轉發到到user服務,/api/shop轉發到到shop服務。zuul預設和Ribbon結合實現了負載均衡的功能, 類似於nginx轉發。

建立Service_Zuul專案

新增配置:

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8888/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul
zuul:
  routes:
    api-a:
      path: /api-member/**
      service-id: service-member #訪問 http://127.0.0.1:8769/api-member/getMemberAll ==》http://127.0.0.1:8762/getMemberAll
    api-b:
      path: /api-order/**
      service-id: service-order #訪問 http://127.0.0.1:8769/api-order/getOrderUserAll ==》http://127.0.0.1:8764/getOrderUserAll

新增依賴:

<?xml version="1.0" encoding="UTF-8"?>
    <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>com.zhang</groupId>
    <artifactId>zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>zuul</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>



</project>

新增Java程式碼

package com.zhang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;


@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZullApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZullApplication.class, args);
    }

}
package com.zhang;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        return true;
    }

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        String refer=request.getHeader("refer");
    
        if (accessToken != null) {
            return null;
        }
        log.warn("token is empty");
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        try {
            ctx.getResponse().getWriter().write("token is empty");
        } catch (Exception e) {
        }
        return null;

    }
}

啟動專案 訪問http://127.0.0.1:8769/api-member/getMemberAll?token=zhang 相當於訪問http://127.0.0.1:8762/getMemberAll

訪問http://127.0.0.1:8769/api-order/getOrderUserAll?token=oo 相當於訪問http://127.0.0.1:8764/getOrderUserAll