spring cloud gateway在请求中增加参数

由于有需要ip的需求,所以在网关层增加ip参数统一传给后端服务

package net.youqu.micro.service.filter;

import net.youqu.micro.service.utils.IpUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * description:
 *
 * @author wangpeng
 * @date 2018/10/18
 */
@Component
public class AddParamFilter implements GatewayFilter, Ordered {
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI uri = exchange.getRequest().getURI();
        StringBuilder query = new StringBuilder();
        String originalQuery = uri.getRawQuery();

        if (StringUtils.hasText(originalQuery)) {
            query.append(originalQuery);
            if (originalQuery.charAt(originalQuery.length() - 1) != '&') {
                query.append('&');
            }
        }
        String remoteHost = IpUtil.getRemoteHost(exchange.getRequest());
        //TODO urlencode?
        query.append("ip");
        query.append('=');
        query.append(remoteHost);
        try {
            URI newUri = UriComponentsBuilder.fromUri(uri)
                    .replaceQuery(query.toString())
                    .build(true)
                    .toUri();

            ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();

            return chain.filter(exchange.mutate().request(request).build());
        } catch (RuntimeException ex) {
            throw new IllegalStateException("Invalid URI query: \"" + query.toString() + "\"");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

}

你可能感兴趣的:(spring cloud gateway在请求中增加参数)