springcloud - eureka 군집 - zuul 게 이 트 웨 이 통합
7116 단어 Java
pom. xml 의존
org.springframework.cloud
spring-cloud-starter-zuul
org.apache.httpcomponents
httpclient
4.5.5
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-security
org.codehaus.groovy
groovy-all
3.0.0-alpha-1
org.springframework.cloud
spring-cloud-starter-config
org.springframework.cloud
spring-cloud-starter-eureka
application.yml
server:
port: 9000
spring:
application:
name: tms-zuul
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 30
lease-expiration-duration-in-seconds: 90
metadata-map:
name: tms-zuul-metadata-map-name
client:
serviceUrl:
defaultZone: http://admin:[email protected]:8761/eureka/, http://admin:[email protected]:8762/eureka/
#
registry-fetch-interval-seconds: 30
zuul:
max:
host:
connections: 500
host:
socket-timeout-millis: 60000
connect-timeout-millis: 60000
routes:
tms-service:
path: /tms-service/**
serviceId: tms-service
tms-service-manager:
path: /tms-service-manager/**
serviceId: tms-service-manager
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 60000
ribbon:
ReadTimeout: 60000
ConnectTimeout: 60000
MaxAutoRetries: 0
MaxAutoRetriesNextServer: 1
endpoints:
sensitive: false
shutdown:
enabled: true
sensitive: true
security:
user:
name: admin
password: admin
role: SUPERUSER
management:
context-path: /tms-zuul
security:
roles: SUPERUSER #
#
logging:
file: logs/logger.log
level:
com.netflix: DEBUG
org.springframework.web: DEBUG
org.springframework.security: INFO
TmsZuulApplication.java
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class TmsZuulApplication {
private final static Logger logger = LoggerFactory.getLogger(TmsZuulApplication.class);
public static void main(String[] args) {
SpringApplication.run(TmsZuulApplication.class, args);
}
/**
* groovy
*/
@Value("${zuul.filter.root}")
private String scriptRoot;
/**
* groovy
*/
@Value("${zuul.filter.refreshInterval}")
private String refreshInterval;
/**
*
*/
@PostConstruct
public void zuulInit(){
FilterLoader.getInstance().setCompiler(new GroovyCompiler());
try {
scriptRoot = scriptRoot + File.separator;
FilterFileManager.setFilenameFilter(new GroovyFileFilter());
FilterFileManager.init(Integer.parseInt(refreshInterval),
scriptRoot + "pre", scriptRoot + "route", scriptRoot + "post");
logger.info("======== zuulInit() ========");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
zuul error 리 턴 인터페이스
@Component
public class TmsServiceFallbackProvider implements ZuulFallbackProvider {
private static Logger logger = LoggerFactory.getLogger(TmsServiceFallbackProvider.class);
@Override
public String getRoute() {
return "ZuulFallbackProvider";
}
@Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return this.getStatusCode().value();
}
@Override
public String getStatusText() throws IOException {
return this.getStatusCode().getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
String msg = "Service Unavailable";
logger.info(msg);
return new ByteArrayInputStream(msg.getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
httpHeaders.setContentType(mediaType);
return httpHeaders;
}
};
}
}
사용자 정의 차단기
@Component
public class MyZuulFilter extends ZuulFilter {
private static Logger logger = LoggerFactory.getLogger(MyZuulFilter.class);
/**
*
* pre:
* routing:
* post: routing error
* error:
* @return
*/
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
/**
* , ,
* @return
*/
@Override
public int filterOrder() {
return 0;
}
/**
* ,
* @return
*/
@Override
public boolean shouldFilter() {
return true;
}
/**
*
* @return
*/
@Override
public Object run() {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
// spring security basic Auth( : , 、 )
requestContext.addZuulRequestHeader("Authorization",
"Basic " + getBase64Credentials("admin", "admin"));
logger.info("======== zuul " + request.getMethod() + " " + request.getRequestURL().toString());
return null;
}
private String getBase64Credentials(String username, String password) {
String plainCreds = username + ":" + password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
return new String(base64CredsBytes);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.