Java编码方式实现spring cloud gateway多filter配置、RedisRateLimiter配置

需求:
把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限流,我在网上没有找到类似的技术贴。最后我把这个问题解决了,并作一个记录。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值