【转】SpringMVC,获取request的几种方法,及线程安全性

做者丨编程迷思html

https://www.cnblogs.com/kismetv/p/8757260.htmljava

 

概述

在使用Spring MVC开发Web系统时,常常须要在处理请求时使用request对象,好比获取客户端ip地址、请求的url、header中的属性(如cookie、受权信息)、body中的数据等。因为在Spring MVC中,处理请求的Controller、Service等对象都是单例的,所以获取request对象时最须要注意的问题,即是request对象是不是线程安全的:当有大量并发请求时,可否保证不一样请求/线程中使用不一样的request对象。web

 

这里还有一个问题须要注意:前面所说的“在处理请求时”使用request对象,到底是在哪里使用呢?考虑到获取request对象的方法有微小的不一样,大致能够分为两类:spring

1)      在Spring的Bean中使用request对象:既包括Controller、Service、Repository等MVC的Bean,也包括了Component等普通的Spring Bean。为了方便说明,后文中Spring中的Bean一概简称为Bean。编程

 

2)      在非Bean中使用request对象:如普通的Java对象的方法中使用,或在类的静态方法中使用。安全

 

此外,本文讨论是围绕表明请求的request对象展开的,但所用方法一样适用于response对象、InputStream/Reader、OutputStream/ Writer等;其中InputStream/Reader能够读取请求中的数据,OutputStream/ Writer能够向响应写入数据。服务器

 

最后,获取request对象的方法与Spring及MVC的版本也有关系;本文基于Spring4进行讨论,且所作的实验都是使用4.1.1版本。cookie

 

如何测试线程安全

 

既然request对象的线程安全问题须要特别关注,为了便于后面的讨论,下面先说明如何测试request对象是不是线程安全的。session

 

测试的基本思路,是模拟客户端大量并发请求,而后在服务器判断这些请求是否使用了相同的request对象。并发

 

判断request对象是否相同,最直观的方式是打印出request对象的地址,若是相同则说明使用了相同的对象。然而,在几乎全部web服务器的实现中,都使用了线程池,这样就致使前后到达的两个请求,可能由同一个线程处理:在前一个请求处理完成后,线程池收回该线程,并将该线程从新分配给了后面的请求。而在同一线程中,使用的request对象极可能是同一个(地址相同,属性不一样)。所以即使是对于线程安全的方法,不一样的请求使用的request对象地址也可能相同。

 

为了不这个问题,一种方法是在请求处理过程当中使线程休眠几秒,这样可让每一个线程工做的时间足够长,从而避免同一个线程分配给不一样的请求;另外一种方法,是使用request的其余属性(如参数、header、body等)做为request是否线程安全的依据,由于即使不一样的请求前后使用了同一个线程(request对象地址也相同),只要使用不一样的属性分别构造了两次request对象,那么request对象的使用就是线程安全的。本文使用第二种方法进行测试。

 

客户端测试代码以下(建立1000个线程分别发送请求):

 1 public class Test {
 2     public static void main(String[] args) throws Exception {
 3         String prefix = UUID.randomUUID().toString().replaceAll("-", "") + "::";
 4         for (int i = 0; i < 1000; i++) {
 5             final String value = prefix + i;
 6             new Thread() {
 7                 @Override
 8                 public void run() {
 9                     try {
10                         CloseableHttpClient httpClient = HttpClients.createDefault();
11                         HttpGet httpGet = new HttpGet("http://localhost:8080/test?key=" + value);
12                         httpClient.execute(httpGet);
13                         httpClient.close();
14                     } catch (IOException e) {
15                         e.printStackTrace();
16                     }
17                 }
18             }.start();
19         }
20     }
21 }

 

服务器中Controller代码以下(暂时省略了获取request对象的代码):

@Controller
public class TestController {

    // 存储已有参数,用于判断参数是否重复,从而判断线程是否安全
    public static Set<String> set = new ConcurrentSkipListSet<>();

    @RequestMapping("/test")
    public void test() throws InterruptedException {

        // …………………………经过某种方式得到了request对象………………………………

        // 判断线程安全
        String value = request.getParameter("key");
        if (set.contains(value)) {
            System.out.println(value + "    重复出现,request并发不安全!");
        } else {
            System.out.println(value);
            set.add(value);
        }

        // 模拟程序执行了一段时间
        Thread.sleep(1000);
    }
}

 

补充:上述代码原使用HashSet来判断value是否重复,经网友批评指正,使用线程不安全的集合类验证线程安全性是欠妥的,现已改成ConcurrentSkipListSet。

若是request对象线程安全,服务器中打印结果以下所示:

若是存在线程安全问题,服务器中打印结果可能以下所示:

 

如无特殊说明,本文后面的代码中将省略掉测试代码。

方法1:Controller中加参数 

代码示例:

这种方法实现最简单,直接上Controller代码:

1 @Controller
2 public class TestController {
3     @RequestMapping("/test")
4     public void test(HttpServletRequest request) throws InterruptedException {
5         // 模拟程序执行了一段时间
6         Thread.sleep(1000);
7     }
8 }

 

该方法实现的原理是,在Controller方法开始处理请求时,Spring会将request对象赋值到方法参数中。除了request对象,能够经过这种方法获取的参数还有不少,具体能够参见:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-methods

Controller中获取request对象后,若是要在其余方法中(如service方法、工具类方法等)使用request对象,须要在调用这些方法时将request对象做为参数传入。

线程安全:

测试结果:线程安全

分析:此时request对象是方法参数,至关于局部变量,毫无疑问是线程安全的。

优缺点:

这种方法的主要缺点是request对象写起来冗余太多,主要体如今两点:

1)      若是多个controller方法中都须要request对象,那么在每一个方法中都须要添加一遍request参数

2)      request对象的获取只能从controller开始,若是使用request对象的地方在函数调用层级比较深的地方,那么整个调用链上的全部方法都须要添加request参数

实际上,在整个请求处理的过程当中,request对象是贯穿始终的;也就是说,除了定时器等特殊状况,request对象至关于线程内部的一个全局变量。而该方法,至关于将这个全局变量,传来传去。

方法2:自动注入

代码示例:

先上代码:

 1 @Controller
 2 public class TestController{
 3 
 4     @Autowired
 5     private HttpServletRequest request; //自动注入request
 6 
 7     @RequestMapping("/test")
 8     public void test() throws InterruptedException{
 9         //模拟程序执行了一段时间
10         Thread.sleep(1000);
11     }
12 }

 

线程安全:

测试结果:线程安全

分析:在Spring中,Controller的scope是singleton(单例),也就是说在整个web系统中,只有一个TestController;可是其中注入的request倒是线程安全的,缘由在于:

使用这种方式,当Bean(本例的TestController)初始化时,Spring并无注入一个request对象,而是注入了一个代理(proxy);当Bean中须要使用request对象时,经过该代理获取request对象。

下面经过具体的代码对这一实现进行说明。

在上述代码中加入断点,查看request对象的属性,以下图所示:

在图中能够看出,request其实是一个代理:代理的实现参见AutowireUtils的内部类ObjectFactoryDelegatingInvocationHandler:

 1 /**
 2  * Reflective InvocationHandler for lazy access to the current target object.
 3  */
 4 @SuppressWarnings("serial")
 5 private static class ObjectFactoryDelegatingInvocationHandler implements InvocationHandler, Serializable {
 6     private final ObjectFactory<?> objectFactory;
 7     public ObjectFactoryDelegatingInvocationHandler(ObjectFactory<?> objectFactory) {
 8         this.objectFactory = objectFactory;
 9     }
10     @Override
11     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
12         // ……省略无关代码
13         try {
14             return method.invoke(this.objectFactory.getObject(), args); // 代理实现核心代码
15         }
16         catch (InvocationTargetException ex) {
17             throw ex.getTargetException();
18         }
19     }
20 }

 

也就是说,当咱们调用request的方法method时,其实是调用了由objectFactory.getObject()生成的对象的method方法;objectFactory.getObject()生成的对象才是真正的request对象。

继续观察上图,发现objectFactory的类型为WebApplicationContextUtils的内部类RequestObjectFactory;而RequestObjectFactory代码以下:

 

 1 /**
 2  * Factory that exposes the current request object on demand.
 3  */
 4 @SuppressWarnings("serial")
 5 private static class RequestObjectFactory implements ObjectFactory<ServletRequest>, Serializable {
 6     @Override
 7     public ServletRequest getObject() {
 8         return currentRequestAttributes().getRequest();
 9     }
10     @Override
11     public String toString() {
12         return "Current HttpServletRequest";
13     }
14 }

 

其中,要得到request对象须要先调用currentRequestAttributes()方法得到RequestAttributes对象,该方法的实现以下:

 1 /**
 2  * Return the current RequestAttributes instance as ServletRequestAttributes.
 3  */
 4 private static ServletRequestAttributes currentRequestAttributes() {
 5     RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
 6     if (!(requestAttr instanceof ServletRequestAttributes)) {
 7         throw new IllegalStateException("Current request is not a servlet request");
 8     }
 9     return (ServletRequestAttributes) requestAttr;
10 }

生成RequestAttributes对象的核心代码在类RequestContextHolder中,其中相关代码以下(省略了该类中的无关代码):

 1 public abstract class RequestContextHolder {
 2     public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
 3         RequestAttributes attributes = getRequestAttributes();
 4         // 此处省略不相关逻辑…………
 5         return attributes;
 6     }
 7     public static RequestAttributes getRequestAttributes() {
 8         RequestAttributes attributes = requestAttributesHolder.get();
 9         if (attributes == null) {
10             attributes = inheritableRequestAttributesHolder.get();
11         }
12         return attributes;
13     }
14     private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
15             new NamedThreadLocal<RequestAttributes>("Request attributes");
16     private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
17             new NamedInheritableThreadLocal<RequestAttributes>("Request context");
18 }

 

经过这段代码能够看出,生成的RequestAttributes对象是线程局部变量(ThreadLocal),所以request对象也是线程局部变量;这就保证了request对象的线程安全性。

优缺点:

该方法的主要优势: 

1)      注入不局限于Controller中:在方法1中,只能在Controller中加入request参数。而对于方法2,不只能够在Controller中注入,还能够在任何Bean中注入,包括Service、Repository及普通的Bean。

2)      注入的对象不限于request:除了注入request对象,该方法还能够注入其余scope为request或session的对象,如response对象、session对象等;并保证线程安全。

3)      减小代码冗余:只须要在须要request对象的Bean中注入request对象,即可以在该Bean的各个方法中使用,与方法1相比大大减小了代码冗余。

可是,该方法也会存在代码冗余。考虑这样的场景:web系统中有不少controller,每一个controller中都会使用request对象(这种场景实际上很是频繁),这时就须要写不少次注入request的代码;若是还须要注入response,代码就更繁琐了。下面说明自动注入方法的改进方法,并分析其线程安全性及优缺点。

 

方法3:基类中自动注入

代码示例:

与方法2相比,将注入部分代码放入到了基类中。

基类代码:

1 public class BaseController {
2     @Autowired
3     protected HttpServletRequest request;     
4 }

Controller代码以下;这里列举了BaseController的两个派生类,因为此时测试代码会有所不一样,所以服务端测试代码没有省略;客户端也须要进行相应的修改(同时向2个url发送大量并发请求)。

 

 1 @Controller
 2 public class TestController extends BaseController {
 3 
 4     // 存储已有参数,用于判断参数value是否重复,从而判断线程是否安全
 5     public static Set<String> set = new ConcurrentSkipListSet<>();
 6 
 7     @RequestMapping("/test")
 8     public void test() throws InterruptedException {
 9         String value = request.getParameter("key");
10         // 判断线程安全
11         if (set.contains(value)) {
12             System.out.println(value + "    重复出现,request并发不安全!");
13         } else {
14             System.out.println(value);
15             set.add(value);
16         }
17         // 模拟程序执行了一段时间
18         Thread.sleep(1000);
19     }
20 }
21 
22 @Controller
23 public class Test2Controller extends BaseController {
24     @RequestMapping("/test2")
25     public void test2() throws InterruptedException {
26         String value = request.getParameter("key");
27         // 判断线程安全(与TestController使用一个set进行判断)
28         if (TestController.set.contains(value)) {
29             System.out.println(value + "    重复出现,request并发不安全!");
30         } else {
31             System.out.println(value);
32             TestController.set.add(value);
33         }
34         // 模拟程序执行了一段时间
35         Thread.sleep(1000);
36     }
37 }

 

线程安全:

测试结果:线程安全

分析:在理解了方法2的线程安全性的基础上,很容易理解方法3是线程安全的:当建立不一样的派生类对象时,基类中的域(这里是注入的request)在不一样的派生类对象中会占据不一样的内存空间,也就是说将注入request的代码放在基类中对线程安全性没有任何影响;测试结果也证实了这一点。

优缺点:

与方法2相比,避免了在不一样的Controller中重复注入request;可是考虑到java只容许继承一个基类,因此若是Controller须要继承其余类时,该方法便再也不好用。

不管是方法2和方法3,都只能在Bean中注入request;若是其余方法(如工具类中static方法)须要使用request对象,则须要在调用这些方法时将request参数传递进去。下面介绍的方法4,则能够直接在诸如工具类中的static方法中使用request对象(固然在各类Bean中也可使用)。

 

方法4:手动调用 

代码示例:

1 @Controller
2 public class TestController {
3     @RequestMapping("/test")
4     public void test() throws InterruptedException {
5         HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
6         // 模拟程序执行了一段时间
7         Thread.sleep(1000);
8     }
9 }

 

线程安全:

测试结果:线程安全

分析:该方法与方法2(自动注入)相似,只不过方法2中经过自动注入实现,本方法经过手动方法调用实现。所以本方法也是线程安全的。

优缺点:

优势:能够在非Bean中直接获取。

缺点:若是使用的地方较多,代码很是繁琐;所以能够与其余方法配合使用。

 

方法5:@ModelAttribute方法

代码示例:

下面这种方法及其变种(变种:将request和bindRequest放在子类中)在网上常常见到:

 1 @Controller
 2 public class TestController {
 3     private HttpServletRequest request;
 4     @ModelAttribute
 5     public void bindRequest(HttpServletRequest request) {
 6         this.request = request;
 7     }
 8     @RequestMapping("/test")
 9     public void test() throws InterruptedException {
10         // 模拟程序执行了一段时间
11         Thread.sleep(1000);
12     }
13 } 

 

线程安全:

测试结果:线程不安全

分析:@ModelAttribute注解用在Controller中修饰方法时,其做用是Controller中的每一个@RequestMapping方法执行前,该方法都会执行。所以在本例中,bindRequest()的做用是在test()执行前为request对象赋值。虽然bindRequest()中的参数request自己是线程安全的,但因为TestController是单例的,request做为TestController的一个域,没法保证线程安全。

总结: 

综上所述,Controller中加参数(方法1)、自动注入(方法2和方法3)、手动调用(方法4)都是线程安全的,均可以用来获取request对象。若是系统中request对象使用较少,则使用哪一种方式都可;若是使用较多,建议使用自动注入(方法2 和方法3)来减小代码冗余。若是须要在非Bean中使用request对象,既能够在上层调用时经过参数传入,也能够直接在方法中经过手动调用(方法4)得到。

此外,本文在讨论获取request对象的方法时,重点讨论该方法的线程安全性、代码的繁琐程度等;在实际的开发过程当中,还必须考虑所在项目的规范、代码维护等问题(此处感谢网友的批评指正)。

相关文章
相关标签/搜索