spring cloud+eureka+fegin+ribbon+hystrix+rabbitMQ+sleuth+zipkin+config+dashboard+zuul大合集开发(四)之zuul集成

在集成网关之前先说下网关存在的必要性,当我们的服务特别多的话,我们不是说所有的服务地址都得暴露给客户端,或者说我们暴露给客户端太多的服务地址也不是很友好,而且也不安全,因此网关的存在就相当于一个门卫,所有的客户端请求可以先通过网关,再由网关转发调用后面的服务,这样就保护了子服务不用直接暴露给客户端,并且所有的请求只需访问网关服务就可以了,再者网关的灵活配置,可以让你有选择性的暴露所需接口给客户对也是很方便。下面就直接上代码把!!!

首先在我前几篇文章的基础上创建新的子工程,也可以单独新建maven工程,起名为server-zuul,给他添加以下依赖

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

  <dependencies>
             <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>4.11</version>
                  <scope>test</scope>
            </dependency>
            <dependency>
    		  <groupId>org.springframework.cloud</groupId>
		  <artifactId>spring-cloud-starter-config</artifactId>
            </dependency>
	    <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>
		    <!-- <version>1.4.6.RELEASE</version> -->
	    </dependency>
  </dependencies>

编写启动类

package org.server.zuul;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.core.env.Environment;
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;

/**
 * Hello world!
 *
 */
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
@RestController
public class ZuulApplication 
{
	
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        new SpringApplicationBuilder(ZuulApplication.class).properties("server.port=8080").run(args);
    }
}

编写配置文件application.yml

spring:
  application:
    name: server-zuul
eureka:
  instance:
    hostname: localhost
    leaseExpirationDurationInSeconds: 30 # 续约到期间间隔(默认90秒)
    leaseRenewalIntervalInSeconds: 10  # 续约更新时间(默认30秒)
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
    healthcheck:
      enabled: true  # 开启健康检查(需要spring-boot-starter-actuator依赖)
management:
  endpoints:
    web:
      exposure:
        include: "*"
  security:
    enabled: false
zuul:
  ignoredPatterns: /sale/noRoute
  routes:
    testZuul:
      path: /testZuul/**
      serviceId: service-invoker	
      

接下来测试,依次启动前三篇文章所写的注册中心,服务提供者,服务调用者,然后再启动该项目,启动完毕后在浏览器访问localhost:8080/testZuul/router

在浏览器接收到1------success则说调用成功

spring cloud+eureka+fegin+ribbon+hystrix+rabbitMQ+sleuth+zipkin+config+dashboard+zuul大合集开发(四)之zuul集成

其实网关也集成了负载均衡,接下来我们验证下网关的负载均衡机制

首先我们对之前的文章创建的服务调用者进行修改,修改启动类的启动方式为可输入端口号的方式

package org.server.invoker;

import java.util.Scanner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
@EnableFeignClients
public class InvokerApp 
{
    public static void main( String[] args )
    {
    	//SpringApplication.run(InvokerApp.class, args);
    	Scanner scan = new Scanner(System.in);
		String port = scan.nextLine();
		new SpringApplicationBuilder(InvokerApp.class).properties("server.port="+port).run(args);
    }
}

然后把其配置文件里面配置的端口号去掉

#server:
#  port: 9000
spring:
  application:
    name: service-invoker
eureka:
  instance:
    hostname: localhost
    leaseExpirationDurationInSeconds: 30 # 续约到期间间隔(默认90秒)
    leaseRenewalIntervalInSeconds: 10  # 续约更新时间(默认30秒)
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
    healthcheck:
      enabled: true  # 开启健康检查(需要spring-boot-starter-actuator依赖)  

为了后面清楚的看到效果,再修改下服务调用者(server-provider)项目的controller下的方法:

package org.server.invoker.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.server.invoker.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.web.client.RestTemplate;




@RestController
@Configuration
public class InvokerController {
	
	@Autowired
	private TestService testService;

	@RequestMapping(value = "/router", method = RequestMethod.GET, 
			produces = MediaType.APPLICATION_JSON_VALUE)
	public String router(HttpServletRequest request) {
		System.out.println(request.getRequestURL().toString());
		for (int i = 0; i < 10; i++) {
			testService.getPersion(i);
		}
		return testService.getPersion(1);
	}
	
}

 

然后重新运行服务调用者的启动类两次,分别输入端口号9001和9002,在注册中心看到两个服务注册成功后多次在浏览器访问localhost:8080/testZuul/router

然后查看服务提供者服务的两个控制台信息可以发现他们被分别请求了

spring cloud+eureka+fegin+ribbon+hystrix+rabbitMQ+sleuth+zipkin+config+dashboard+zuul大合集开发(四)之zuul集成

spring cloud+eureka+fegin+ribbon+hystrix+rabbitMQ+sleuth+zipkin+config+dashboard+zuul大合集开发(四)之zuul集成

由此可见网关自动集成了负载均衡在里面,当然网关最主要的还是在路由的配置,网关为了保证转发性能,使用了httpClient的连接池功能,因此可以设置目标主机的最大连接数,初始连接数等等,也可以自定义编写其过滤器(继承ZuulFilter),处理一些验证等等,也可以定义过滤器的优先级,可以根据需求写多个过滤器,然后在配置文件中配置,也可以根据需求编写回退处理逻辑,需要实现ZuulFallbackProvider接口,黑客进行异常过滤,等等,网关除了能够路由进自己所在集群的服务,还可以转发至第三方网站,所以还是相当灵活的,具体这些配置的实现此篇文章就不过多多介绍了,想了解的可以查看官方文档,篇幅有限,后面的有机会再做具体介绍,先溜了。。。。。。。。。。

 

下一篇将再介绍Hystrix监控服务Dashboard的搭建,将对整个服务的健康情况以及每个请求的走向进行监控,对数据进行可视化查看。