Spring Cloud 제6 편: 게 이 트 웨 이 (zuul)
13891 단어 spring-cloud
:module:spring-cloud-service-zuul
Spring Cloud 마이크로 서비스 시스템 에서 흔히 볼 수 있 는 부하 균형 방식 은 클 라 이언 트 의 요청 이 먼저 부하 균형 (zuul, Ngnix) 을 거 쳐 서비스 게 이 트 웨 이 (zuul 군집) 에 도착 한 다음 에 구체 적 인 서버 에 도착 하 는 것 이다.서 비 스 는 사용 가능 한 서비스 등록 센터 클 러 스 터 에 통일 적 으로 등록 되 어 있 습 니 다. 서비스의 모든 프로필 은 설정 서비스 에 의 해 관리 되 고 서 비 스 를 설정 하 는 프로필 은 git 창고 에 두 어 개발 자 들 이 수시로 설정 을 바 꾸 도록 합 니 다.
6.1 Zuul 소개
Zuul 의 주요 기능 은 퍼 가기 와 필터 입 니 다.경로 기능 은 마이크로 서비스의 일부분 입 니 다. 예 를 들 어 / api / user 는 user 서비스 로 전송 하고 / api / shop 은 shop 서비스 로 전송 합 니 다.zuul 은 기본적으로 Ribbon 과 결합 하여 부하 균형 기능 을 실현 했다.
zuul 은 다음 과 같은 기능 이 있 습 니 다.
Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
Load Shedding
Security
Static Response handling
Active/Active traffic management
6.2 준비 작업
지난 절의 공 사 를 계속 사용 하 다.기 존 프로젝트 에 새 프로젝트 를 만 듭 니 다.
6.3 spring - cloud - service - zuul 프로젝트 만 들 기
POM 참조:
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-netflix-zuul
org.springframework.boot
spring-boot-starter-test
test
6.4 시작 클래스 수정
입구 application 클래스 에 주석 @ EnableZuulProxy 를 추가 하여 zuul 기능 을 엽 니 다.
/**
* @author sunjiamin
*/
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
public class SpringCloudServiceZuulApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudServiceZuulApplication.class, args);
}
}
6.5 프로필 수정
프로필 application. yml 에 다음 설정 코드 를 추가 합 니 다.
eureka:
client:
serviceUrl:
defaultZone: http://localhost:7070/eureka/
server:
port: 7077
spring:
application:
name: service-zuul
zuul:
routes:
api-a:
path: /api-a/**
# /api-a/ service-ribbon ;
serviceId: service-ribbon
api-b:
path: /api-b/**
# /api-b/ service-feign ;
serviceId: service-feign
이 다섯 개의 공 사 를 순서대로 운행 하 다.브 라 우 저 접근 열기:http://localhost:7077/api-a/hi?name=jojo ;브 라 우 저 디 스 플레이:
hi jojo,i am from port:7072
브 라 우 저 접근 열기:http://localhost:7077/api-b/hi?name=jojo ;브 라 우 저 디 스 플레이:
hi jojo,i am from port:7072
6.6 서비스 필터
zuul 은 경로 뿐만 아니 라 여과 도 할 수 있 고 안전 검증 도 할 수 있 습 니 다.계속 개조 공사;ZuulFilter 에서 MyFilter 계승 추가:
package com.sun.jojo.servicezuul.config;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* description:
*
* @author sunjiamin
* @date 2018-05-14 15:24
*/
@Component
public class MyFilter extends ZuulFilter{
private static Logger log = LoggerFactory.getLogger(MyFilter.class);
/**
* filterType: , zuul , :
* pre:
* routing:
* post:
* error:
* @return
*/
@Override
public String filterType() {
return "pre";
}
/**
* filterOrder:
* @return
*/
@Override
public int filterOrder() {
return 0;
}
/**
* shouldFilter: , , true, 。
* @return
*/
@Override
public boolean shouldFilter() {
return true;
}
/**
* run: 。 , sql,nosql 。
* @return
* @throws ZuulException
*/
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken = request.getParameter("token");
if(accessToken == 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;
}
log.info("ok");
return null;
}
}
이 때 접근:http://localhost:7077/api-a/hi?name=jojo ;웹 페이지 표시:
token is empty
방문 하 다. http://localhost:7077/api-a/hi?name=jojo&token=22 ; 웹 페이지 표시:
hi joj0,i am from port:7072