[Redis] redis Distributed Lock (II)

In a blog post, to be distributed lock the test, wrote several tested the service. Bowen Address:

https://www.cnblogs.com/wuyizuokan/p/11111313.html

There is a use of the Java language, using SpringBoot framework of simple Web services, Rest provides several interfaces, including interfaces PUT and GET interfaces are idempotent, setting a count value, a query count value; addition of an interface is POST , it is used to modify the value of the calculator. Of course, in principle, to adopt the words of Restful style, POST function interface is not consistent Restful style.

There is also a language using the Go, call interface for Web services, distributed lock to discuss here does not use POST interfaces, but the combination of interfaces and Post Get Interface, why not use POST interface to it? Because Web services are too simple, and it has been used internally synchronized to prevent multiple threads access problems, we can only use atomic composition Get Interface and POST interface to operate the.

The last written in Python, and it is used to call Web services, programs above.

 

First, we define written in Java Web services producer services, use the Go language service for Go consumer services, written in Python Python services for consumer services.

Here simulation test scenario is this:

Two Consumer Services 1000 cycles, each cycle, first query the value of the Count, and then add to Count 20, then use the new interface settings PUT Count value.

Flowchart consumers is simple:

Here is the consumer code:

Go:

func main(){
	for i:= 1000; i > 0;i--  {
		count,err := getCount()
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Println("the count is: ", count)
		count += 20

		setCount(count)
	}
}

  

Python:

if __name__=="__main__":
    n = 1000
    while n > 0:
        count = getCount()  # 测试查询Count
        print("the count is:", count)
        count += 20
        setCount(count)
        n = n - 1

 

首先做一下分析,如果两个消费者的动者都能成功,count的值将会增加1000 * 20 *2 = 40000。当然,因为存在访问共享资源,且消费者的动作没有原子性,很可能无法达到增加40000的效果。

首先单独运行一遍go消费者和python消费者,不让它们并行运行,预期的值应该是40000:

go消费者运行:

使用postman查询结果:

然后运行Python消费者:

使用postman查询结果:

符合预期。

 

下面进行测试,为了便于测试,首先初始化Count的值为0:

同时启动go消费者和python消费者:

 

 使用Postman查询Count的最终结果:

35080,很明显没有达到40000,符合预期的因为没有锁机制导致的共享资源的错误。

 

接下来,会使用redis来做一个分布式锁,看看如何使用redis来保证多个服务间访问共享数据的安全性。

当然,后面还会使用zookeeper来做分布式锁的实验,相对于redis来说,我更喜欢使用zookeeper的分布式锁方案。

 

Guess you like

Origin www.cnblogs.com/wuyizuokan/p/11300084.html