SpringBoot学习总结(6)之整合Filter

一、环境

Maven 3.6.0
IDEA IntelliJ IDEA 2017.2.6 x64
JDK 1.8
Spring Boot 1.5.4.RELEASE

二、pom.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.mqc</groupId>
	<artifactId>springboot-mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-mybatis</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

三、整合方式一:通过注解扫描方式完成Filter组件的注册

编写Filter:

package com.mqc.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author maoqichuan
 * @ClassName: annotationFilter
 * @description: 通过注解扫描方式完成Filter组件的注册
 * @date 2019-04-099:44
 * 以往我们要完成一个拦截器,首先就是要编写对应的拦截器类,其次就是要在web.xml中配置拦截器
 *<filter>
 * <filter-name>FirstFilter</filter-name>
 * <filter-class>com.bjsxt.filter.FirstFilter</filter-class>
 *</filter>
 *<filter-mapping>
 * <filter-name>FirstFilter</filter-name>
 * <url-pattern>/first</url-pattern>
 *</filter-mapping>
 **/
@WebFilter(filterName = "AnnotationFilter",urlPatterns = "/annotationFilter")
public class AnnotationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.print("完成拦截器的初始化,在创建拦截器的时候自动调用");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.print("进入拦截器");
        //模拟预处理
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.print("退出拦截器");
    }

    @Override
    public void destroy() {
        System.out.print("在销毁拦截器的时候自动调用");
    }
}

@WebFilter,标记这是一个拦截器类,FilterName属性表示这个拦截器的名字,urlPatterns为这个拦截器的拦截器请求路径。

编写对应的启动类,在上一篇博文中我已经介绍了SpringBoot如何整合Servlet,其中已经介绍了@ServletComponentScan的作用主要是什么,有需要的可以查看https://blog.csdn.net/jokeMqc/article/details/89087714,其实@ServletComponentScan在springBoot 启动时会扫描@WebFilter,并将该类实例化,在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。

package com.mqc;


import com.mqc.servlet.MyServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;


/**
 * @description: springboot整合Filter方式一:通过@ServletComponentScan注解扫描方式完成Filter组件的注册
 * @author maoqichuan
 * @date 2019-04-08 16:17
 */
@SpringBootApplication
@ServletComponentScan
public class SpringbootMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootMybatisApplication.class, args);
	}


}

调试,启动项目,可以看到我们写的Filter组件已经 被扫描到并且实例化了。

在浏览器输入:http://localhost:8080/annotationFilter

四、整合方式二:通过方法完成Filter 组件的注册

编写Filter。

package com.mqc.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author maoqichuan
 * @ClassName: MethodFilter
 * @description: SpringBoot整合Filter方式二:通过方法注册Filter组件
 * @date 2019-04-0910:09
 **/
public class MethodFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("完成MethodFilter组件的注册");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入--->>MethodFilter拦截器");
        try {
            // 模拟
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("退出--->>MethodFilter拦截器");
    }

    @Override
    public void destroy() {

    }
}

编写启动类。

package com.mqc;


import com.mqc.filter.MethodFilter;
import com.mqc.servlet.MyServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;


/**
 * @description: springboot整合Filter方式二:通过方法完成Filter组件的注册
 * @author maoqichuan
 * @date 2019-04-08 16:17
 */
@SpringBootApplication

public class SpringbootMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootMybatisApplication.class, args);
	}

	/**
	 * @description: 通过方法完成Filter组件的注册
	 * @return FilterRegistrationBean
	 * @throws
	 * @author maoqichuan
	 * @date 2019-04-09 10:14
	 */
	@Bean
	public FilterRegistrationBean getFilterRegistrationBean(){
		FilterRegistrationBean bean = new FilterRegistrationBean(new MethodFilter());

		bean.addUrlPatterns("/methodFilter");
		return bean;
	}
}

在浏览器中输入:http://localhost:8080/methodFilter

到这里,SpringBoot整合Filter的两种方式到这里就已经是整合完毕了,大家有什么问题都可以私信我,让我们大家一起进步,一起努力,一起加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Spring Boot整合Spring Cloud Alibaba Gateway并使用Redis进行缓存的步骤: 1. 创建Spring Boot工程,添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis 在application.properties文件中添加以下配置: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 配置Gateway 在application.yml文件中添加以下配置: ``` spring: cloud: gateway: routes: - id: test_route uri: http://localhost:8080 predicates: - Path=/test/** filters: - name: RequestRateLimiter args: key-resolver: "#{@userKeyResolver}" redis-rate-limiter.replenishRate: 1 redis-rate-limiter.burstCapacity: 2 user: rate-limiter: redis: prefix: "rate-limiter" remaining-key: "remaining" reset-key: "reset" ``` 其中: - id:路由ID - uri:目标服务的URL - predicates:路由断言,此处表示只有访问/test/**的请求才会被路由到目标服务 - filters:路由过滤器,此处使用了RequestRateLimiter过滤器,用于限流 4. 编写Redis限流过滤器 在工程中创建一个RedisRatelimiterFilter类,实现GatewayFilter和Ordered接口,并重写filter方法。 ``` @Component public class RedisRatelimiterFilter implements GatewayFilter, Ordered { private final RedisTemplate<String, String> redisTemplate; private final StringRedisTemplate stringRedisTemplate; private final ObjectMapper objectMapper; public RedisRatelimiterFilter(RedisTemplate<String, String> redisTemplate, StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) { this.redisTemplate = redisTemplate; this.stringRedisTemplate = stringRedisTemplate; this.objectMapper = objectMapper; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String key = "rate-limiter:" + exchange.getRequest().getPath().value(); String remainingKey = key + ":remaining"; String resetKey = key + ":reset"; return redisTemplate.execute(script, Collections.singletonList(remainingKey), "1", "2") .flatMap(result -> { String json = objectMapper.writeValueAsString(result); Map<String, Object> map = objectMapper.readValue(json, Map.class); int remaining = (int) map.get("remaining"); long reset = (long) map.get("reset"); exchange.getResponse().getHeaders().add("X-RateLimit-Remaining", String.valueOf(remaining)); exchange.getResponse().getHeaders().add("X-RateLimit-Reset", String.valueOf(reset)); if (remaining < 0) { exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } return stringRedisTemplate.opsForValue().increment(remainingKey) .flatMap(result2 -> { if (result2.equals(1L)) { stringRedisTemplate.expire(resetKey, Duration.ofMinutes(1)); } return chain.filter(exchange); }); }); } private static final RedisScript<List<Long>> script = RedisScript.of( "local key = KEYS[1]\n" + "local now = tonumber(ARGV[1])\n" + "local rate = tonumber(ARGV[2])\n" + "local capacity = tonumber(ARGV[3])\n" + "local remaining = redis.call('get', key)\n" + "if remaining then\n" + " remaining = tonumber(remaining)\n" + "else\n" + " remaining = capacity\n" + "end\n" + "if remaining == 0 then\n" + " return {0, 0}\n" + "else\n" + " local reset\n" + " if remaining == capacity then\n" + " reset = now + 60\n" + " redis.call('set', key..\":reset\", reset)\n" + " else\n" + " reset = tonumber(redis.call('get', key..\":reset\"))\n" + " end\n" + " local ttl = reset - now\n" + " local ratePerMillis = rate / 1000\n" + " local permits = math.min(remaining, ratePerMillis * ttl)\n" + " redis.call('set', key, remaining - permits)\n" + " return {permits, reset}\n" + "end\n", ReturnType.MULTI, Collections.singletonList("remaining") ); @Override public int getOrder() { return -1; } } ``` 5. 编写KeyResolver 在工程中创建一个UserKeyResolver类,实现KeyResolver接口,并重写resolve方法。 ``` @Component public class UserKeyResolver implements KeyResolver { @Override public Mono<String> resolve(ServerWebExchange exchange) { String userId = exchange.getRequest().getQueryParams().getFirst("userId"); return Mono.justOrEmpty(userId); } } ``` 6. 测试 启动工程,访问http://localhost:8080/test,可以看到返回结果为“Hello, world!”;再次访问http://localhost:8080/test,可以看到返回结果为“Too Many Requests”。 以上就是Spring Boot整合Spring Cloud Alibaba Gateway并使用Redis进行缓存的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值