springcloud全家桶个人博客系统(八)使用gateway代替zull

一、前言

由于zull不在维护更新,springcloud官方推荐使用gateway代替zull。所以我们就代替一下子。

二、添加blog_gateway模块

springcloud全家桶个人博客系统(八)使用gateway代替zull_第1张图片

(1)引入pom文件


        
        
            org.springframework.cloud
            spring-cloud-starter-gateway
        
        
            org.springframework.cloud
            spring-cloud-starter-alibaba-nacos-discovery
            0.9.0.RELEASE
        
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.projectlombok
            lombok
        
    

注意:这里有个大坑,使用gateway,千万不要引入boot-web以及jetty坐标,否则会引起jar包冲突 。

(2)添加main

@SpringBootApplication
@EnableDiscoveryClient
public class Gateway {
        public static void main(String[] args) {
            SpringApplication.run(Gateway.class, args);
        }
}

(3)添加application.properties

server.port=9527

spring.application.name=blog_gateway


spring.cloud.nacos.discovery.server-addr=localhost:8848

spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.routes[0].id=blog-consumer-feign
spring.cloud.gateway.routes[0].uri=lb://blog-consumer-feign
spring.cloud.gateway.routes[0].predicates[0]= Path=/**

info.app.name=blog_gateway
info.company.name=www.sustly.cn
info.build.artifactId=${project.artifactId}
info.build.version=${project.version}

 这里注意,uri和他对应的path要符合规则,否则访问不到的

id随便取

spring.cloud.gateway.routes[0].uri 这个是要路由的微服务

spring.cloud.gateway.routes[0].predicates[0] 路由断言,和路由一起匹配访问的路径

(4)自定义filter拦截日志

@Configuration
@Slf4j
public class LogsFilter implements GlobalFilter, Ordered {

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        log.info("path: " + request.getPath());
        log.info("address: " + request.getRemoteAddress());
        log.info("method: " + request.getMethodValue());
        log.info("URI: " + request.getURI());
        log.info("Headers: " + request.getHeaders());
        Object requestBody = exchange.getAttribute("cachedRequestBodyObject");
        log.info("body: "+ requestBody);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }


}

 

你可能感兴趣的:(springcloud全家桶个人博客系统(八)使用gateway代替zull)