springcloud - eureka 군집 - zuul 게 이 트 웨 이 통합

7116 단어 Java
springcloud - eureka 군집 - zuul 게 이 트 웨 이 통합
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);
    }
}

좋은 웹페이지 즐겨찾기