需求:
把yml中的route配置:
/**
* 使用java编码的方式,替换原先yml中路由2的配置:
* #考虑到要采用ip白名单,将路由2改为java配置
- id: accessProvider #路由2:要想访问后台微服务,请求头中就必须要含有CMSOFT_TOKEN才能实现路由转发!!
uri: lb://provider
predicates:
- Path=/provider-service/**
- RemoteAddr=127.0.0.1,0:0:0:0:0:0:0:1 #后者是ipv6格式的本机ip
filters:
- StripPrefix=1 #去掉Path中的/provider-service
- name: RequestRateLimiter #这个名字不能动
args:
key-resolver: '#{@globalKeyResolver}'
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 10
* @author FUZIYAN
*
*/
转变为,java编码的格式
@Component
public class AccessProvider {
@Autowired(required = true)
private WhiteIpConfiguration whiteIps;
@Autowired
GlobalKeyResolver globalKeyResolver;
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver.maxTrustedIndex(1);
// private static final String[] whiteAddress={
// "127.0.0.1","0:0:0:0:0:0:0:1","192.168.0.1"
// }; //代码写死,不利于后期配置维护和更改。采用@PropertySource搭配@Value从.properties文件动态取值
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
String[] whiteAddress = whiteIps.getIps();
return builder.routes().route("accessProvider", r -> r.path("/provider-service/**").and()
.remoteAddr(resolver, whiteAddress).filters(f -> f.stripPrefix(1).requestRateLimiter()
.rateLimiter(RedisRateLimiter.class, c -> c.setBurstCapacity(10).setReplenishRate(10))
.configure(c -> c.setKeyResolver(globalKeyResolver))).uri("lb://provider")).build();
}
}
其中,WhiteIpConfiguration内容为:
@Component
@PropertySource(value = {"classpath:/properties/whiteIpAddress.properties"})
public class WhiteIpConfiguration {
@Value("${whiteIps}")
private String ip;
public String[] getIps() {
return ip.split(",");
}
@Override
public String toString() {
return "WhiteIpConfiguration [ip=" + ip + "]";
}
}
事情起因经过:
最近项目基于spring cloud gateway开发网关,有一个需求是添加ip白名单。因为yml中配置是固定的,所以我的想法是在properties配置文件中添加放行ip address,然后使用@propertySource和@Value用一个pojo对象封装ip地址信息。从而使用java编码方式实现route功能,在其中@Autowired该pojo对象,实现ip白名单的灵活更换。
所以,目的就是要将原先yml中route的配置改成以java编码的方式。原先的yml中有多个filter,并且还引入了redisratelimiter来做qps限流,我在网上没有找到类似的技术贴。最后我把这个问题解决了,并作一个记录。