---
title: "web server 多进程处理web请求遇到的一些问题"
author: "wangleide414"
date: "2016-03-16T12:18:37Z"
tags: []
categories: ["行业应用"]
slug: "web-server-web"
draft: false
lastmod: "2016-03-16T12:26:14Z"
id: 2278366
url: "https://wangleide414.iteye.com/blog/2278366"
---

uwsgi 处理web 请求使用了多进程的模式，接收到web请求后可能由不同的进程去处理。

 

问题背景：

 一、前段时间写了个api,  这个api 是在django项目中的，并且使用的是nginx+uwsgi的方式提供服务的。在api  中 使用了django 的 get\_or\_create来保证数据表的唯一性。

           

```
XXX.objects.get_or_create(custom_column_id=custom_column_id, l_id=l_id)
```

 

 

 二、调用这个api 的客户端只有一个进程，并且使阻塞式的串行调用，只有在第一个接口返回后才进行下一次的请求。

 三、结果经过长期的运行发现，数据表中多了很多重复的数据。

   

custom\_column\_id l\_id 1 2 1 2

 

**问题分析：** 先查查get\_or\_create的源代码，发现其不是线程安全的。也就是说有两个进程或线程在同时执行的get\_or\_create的时候，可能会都进行Create，这样就会产生两条相同的数据。如下django 源码：

```
def get_or_create(self, defaults=None, **kwargs):
        """
        Looks up an object with the given kwargs, creating one if necessary.
        Returns a tuple of (object, created), where created is a boolean
        specifying whether an object was created.
        """
        lookup, params = self._extract_model_params(defaults, **kwargs)
        # The get() needs to be targeted at the write database in order
        # to avoid potential transaction consistency problems.
        self._for_write = True
        try:
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            return self._create_object_from_params(lookup, params)
```

 

也就是说如果uwsgi 的多进程在同时并发处理请求时可能会导致这种重复的数据产生。但是疑惑的是，客户端是串行请求的。在一个请求完成后在发送另一个请求。仔细研究代码发现发送请求使用python的requests 库，并且加了timeout 限制，如下官方解释：

 

```
You can tell Requests to stop waiting for a response after a given number of seconds with the timeout parameter:
requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
```

 

也就是在timeout范围内没有收到响应，客户端就会结束。虽然客户端停止了，但是服务端还没有结束，这时候再处理同样的请求就可能会并发的调用get\_or\_create方法，造成重复数据的问题。做一个实验来证明request 在timeout 后，客户端停止了。但是服务端依然在处理。如下图，客户端在timeout=3 s 后就自动返回，然而服务端依然在运行，知道uwsgi超时后自动重启。

   
![](http://dl2.iteye.com/upload/attachment/0115/8320/a36e7dbf-052f-3b87-86e5-f928800eb768.png)图一、客户端超时返回错误  
   
![](http://dl2.iteye.com/upload/attachment/0115/8322/d69af64f-5cdf-3eac-bca5-79cbff52acdd.png) 图二、服务端使用循环输出来验证

![](http://dl2.iteye.com/upload/attachment/0115/8324/5a390426-a0f9-3b62-99bf-443bbead9d29.png) 图三，服务端在超时后才退出

 

 

注:uwsgi 是使用进程池的方式处理http请求，也就是每次请求到来的请求可能是不同的进程去处理的。当然在uwsgi 中可以配置请求处理的超时时间，如果在超时时间内还没有处理完，主进程会把这个处理请求的进程重启。

 

解决思路： 

一，调整调用api 时设置的超时时间，保证接受请求的api进程处理完毕。超时时间必须大于uwsgi进程的超时时间（目前使用该方法，观察了一个月没有数据重复的情况）。

二，如果能在数据库层面保证数据的唯一性是最好的。那样才能保证数据的唯一性。