├── .CHANGELOG.md ├── script ├── lua │ ├── unlock.lua │ ├── refresh.lua │ └── lock.lua ├── goimports.sh ├── docker-compose.yml ├── integrate_test.sh └── setup.sh ├── .licenserc.json ├── demo ├── unlock.lua ├── lock.lua ├── refresh.lua ├── demo_e2e_test.go ├── demo_test.go └── demo.go ├── README.md ├── .gitignore ├── .github ├── ISSUE_TEMPLATE │ ├── refactor.md │ ├── question.md │ ├── feature_request.md │ └── bug_report.md ├── pre-commit ├── workflows │ ├── license.yml │ ├── stale.yml │ ├── go.yml │ ├── go-fmt.yml │ └── golangci-lint.yml └── pre-push ├── .license.go.header ├── go.mod ├── .golangci.yml ├── .deepsource.toml ├── Makefile ├── retry.go ├── .codecov.yml ├── go.sum ├── lock.go ├── lock_e2e_test.go ├── LICENSE └── lock_test.go /.CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 开发中 2 | - [完成代码和测试](https://github.com/gotomicro/redis-lock/pull/1) -------------------------------------------------------------------------------- /script/lua/unlock.lua: -------------------------------------------------------------------------------- 1 | if redis.call("get", KEYS[1]) == ARGV[1] 2 | then 3 | return redis.call("del", KEYS[1]) 4 | else 5 | return 0 6 | end -------------------------------------------------------------------------------- /script/lua/refresh.lua: -------------------------------------------------------------------------------- 1 | if redis.call("get", KEYS[1]) == ARGV[1] 2 | then 3 | return redis.call("expire", KEYS[1], ARGV[2]) 4 | else 5 | return 0 6 | end -------------------------------------------------------------------------------- /.licenserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "**/*.go": "// Copyright 2021 gotomicro", 3 | "**/*.{yml,toml}": "# Copyright 2021 gotomicro", 4 | "**/*.sh": "# Copyright 2021 gotomicro" 5 | } -------------------------------------------------------------------------------- /demo/unlock.lua: -------------------------------------------------------------------------------- 1 | -- 两个动作:1. 检测是不是预期中的值(也就是,是不是你的锁); 2 | -- 2. 如果是,删除;如果不是,返回一个值 3 | if redis.call("get", KEYS[1]) == ARGV[1] then 4 | return redis.call("del", KEYS[1]) 5 | else 6 | -- 返回 0 代表的是 key 不在,或者值不对 7 | return 0 8 | end -------------------------------------------------------------------------------- /demo/lock.lua: -------------------------------------------------------------------------------- 1 | if redis.call("get", KEYS[1]) == ARGV[1] 2 | then 3 | -- 刷新过期时间 4 | return redis.call("pexpire", KEYS[1], ARGV[2]) 5 | else 6 | -- 设置 key value 和过期时间 7 | return redis.call("set", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) 8 | end -------------------------------------------------------------------------------- /demo/refresh.lua: -------------------------------------------------------------------------------- 1 | -- 两个动作:1. 检测是不是预期中的值(也就是,是不是你的锁); 2 | -- 2. 如果是,删除;如果不是,返回一个值 3 | if redis.call("get", KEYS[1]) == ARGV[1] then 4 | return redis.call("pexpire", KEYS[1], ARGV[2]) 5 | else 6 | -- 返回 0 代表的是 key 不在,或者值不对 7 | return 0 8 | end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # redis-lock 2 | 基于 Redis 实现的分布式锁。要求: 3 | - Redis >= v7: 理论上来说低于 Redis 7 的也可以,但是暂时我还没在这些 Redis 版本上测试 4 | - Go >= 18: 低版本的 Go 应该也可以,只要能够编译通过就可以 5 | 6 | ## 关于极客时间课程 7 | 8 | demo 文件夹的内容是我在极客时间讲如何实现一个分布式锁的时候现场写下的代码,虽然里面有 BUG,但是我还是保留了下来。 9 | 10 | 真正可用的代码就在这个目录下,demo 中的只是用来辅助学习极客时间的。 11 | 12 | ## 加入我们 13 | - [贡献指南](http://ekit.gocn.vip/contribution/) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | .idea 17 | **/.DS_Store -------------------------------------------------------------------------------- /script/lua/lock.lua: -------------------------------------------------------------------------------- 1 | local val = redis.call('get', KEYS[1]) 2 | -- 在加锁的重试的时候,要判断自己上一次是不是加锁成功了 3 | if val == false then 4 | -- key 不存在 5 | return redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[2]) 6 | elseif val == ARGV[1] then 7 | -- 刷新过期时间 8 | redis.call('expire', KEYS[1], ARGV[2]) 9 | return "OK" 10 | else 11 | -- 此时别人持有锁 12 | return "" 13 | end -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/refactor.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Refactor request 3 | about: Refactor existing code 4 | title: '' 5 | labels: refactor 6 | assignees: '' 7 | 8 | --- 9 | 10 | **仅限中文** 11 | 12 | ### 当前实现缺陷 13 | 14 | ### 重构方案 15 | > 描述可以如何重构,以及重构之后带来的效果,如可读性、性能等方面的提升 16 | 17 | ### 其它 18 | > 任何你觉得有利于解决问题的补充说明 19 | 20 | ### 你使用的是 redis-lock 哪个版本? 21 | 22 | ### 你设置的的 Go 环境? 23 | > 上传 `go env` 的结果 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Want to ask some questions 4 | title: '' 5 | labels: question 6 | --- 7 | 8 | **仅限中文** 9 | 10 | 在提之前请先查找[已有 issues](https://github.com/gotomicro/redis-lock/issues),避免重复上报。 11 | 12 | 并且确保自己已经: 13 | - [ ] 阅读过文档 14 | - [ ] 阅读过注释 15 | - [ ] 阅读过例子 16 | 17 | ### 你的问题 18 | 19 | ### 你使用的是 redis-lock 哪个版本? 20 | 21 | ### 你设置的的 Go 环境? 22 | > 上传 `go env` 的结果 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: feature 6 | assignees: '' 7 | 8 | --- 9 | 10 | **仅限中文** 11 | 12 | ### 使用场景 13 | 14 | ### 行业分析 15 | > 如果你知道有框架提供了类似功能,可以在这里描述,并且给出文档或者例子 16 | 17 | ### 可行方案 18 | > 如果你有设计思路或者解决方案,请在这里提供。你可以提供多个方案,并且给出自己的选择 19 | 20 | ### 其它 21 | > 任何你觉得有利于解决问题的补充说明 22 | 23 | ### 你使用的是 redis-lock 哪个版本? 24 | 25 | ### 你设置的的 Go 环境? 26 | > 上传 `go env` 的结果 27 | -------------------------------------------------------------------------------- /.license.go.header: -------------------------------------------------------------------------------- 1 | Copyright 2021 gotomicro 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/gotomicro/redis-lock 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/google/uuid v1.3.0 7 | github.com/redis/go-redis/v9 v9.3.0 8 | github.com/stretchr/testify v1.8.1 9 | golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0 10 | ) 11 | 12 | require ( 13 | github.com/cespare/xxhash/v2 v2.2.0 // indirect 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect 16 | github.com/pmezard/go-difflib v1.0.0 // indirect 17 | go.uber.org/mock v0.3.0 // indirect 18 | gopkg.in/yaml.v3 v3.0.1 // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **仅限中文** 11 | 12 | 在提之前请先查找[已有 issues](https://github.com/gotomicro/redis-lock/issues),避免重复上报。 13 | 14 | 并且确保自己已经: 15 | - [ ] 阅读过文档 16 | - [ ] 阅读过注释 17 | - [ ] 阅读过例子 18 | 19 | ### 问题简要描述 20 | 21 | ### 复现步骤 22 | > 请提供简单的复现代码 23 | 24 | ### 错误日志或者截图 25 | 26 | ### 你期望的结果 27 | 28 | ### 你排查的结果,或者你觉得可行的修复方案 29 | > 可选。我们希望你能够尽量先排查问题,帮助我们减轻维护负担。这对于你个人能力提升同样是有帮助的。 30 | 31 | ### 你使用的是 redis-lock 哪个版本? 32 | 33 | ### 你设置的的 Go 环境? 34 | > 上传 `go env` 的结果 -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | run: 16 | go: '1.18' 17 | skip-dirs: 18 | - .idea -------------------------------------------------------------------------------- /script/goimports.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | goimports -l -w $(find . -type f -name '*.go' -not -path "./.idea/*") -------------------------------------------------------------------------------- /script/docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | services: 15 | redis: 16 | image: docker.io/bitnami/redis:7.0 17 | environment: 18 | - ALLOW_EMPTY_PASSWORD=yes 19 | ports: 20 | - '6379:6379' -------------------------------------------------------------------------------- /script/integrate_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Copyright 2021 gotomicro 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | docker compose -f script/docker-compose.yml down 18 | docker compose -f script/docker-compose.yml up -d 19 | go test -race ./... -tags=e2e 20 | docker compose -f script/docker-compose.yml down 21 | -------------------------------------------------------------------------------- /.deepsource.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | version = 1 16 | 17 | [[analyzers]] 18 | name = "go" 19 | enabled = true 20 | 21 | [analyzers.meta] 22 | import_root = "github.com/gotomicro/redis-lock" 23 | dependencies_vendored = false 24 | 25 | [[analyzers]] 26 | name = "test-coverage" 27 | enabled = true 28 | 29 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: bench 2 | bench: 3 | @go test -bench=. -benchmem ./... 4 | 5 | .PHONY: ut 6 | ut: 7 | @go test -race ./... 8 | 9 | .PHONY: setup 10 | setup: 11 | @sh ./script/setup.sh 12 | 13 | .PHONY: fmt 14 | fmt: 15 | @sh ./script/goimports.sh 16 | 17 | .PHONY: lint 18 | lint: 19 | @golangci-lint run -c .golangci.yml 20 | 21 | .PHONY: tidy 22 | tidy: 23 | @go mod tidy -v 24 | 25 | .PHONY: check 26 | check: 27 | @$(MAKE) fmt 28 | @$(MAKE) tidy 29 | 30 | # e2e 测试 31 | .PHONY: e2e 32 | e2e: 33 | sh ./script/integrate_test.sh 34 | 35 | .PHONY: e2e_up 36 | e2e_up: 37 | docker compose -f script/docker-compose.yml up -d 38 | 39 | .PHONY: e2e_down 40 | e2e_down: 41 | docker compose -f script/docker-compose.yml down 42 | 43 | .PHONY: mock 44 | mock: 45 | mockgen -copyright_file=.license.go.header -package=mocks -destination=mocks/redis_cmdable.mock.go github.com/redis/go-redis/v9 Cmdable -------------------------------------------------------------------------------- /.github/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Copyright 2021 gotomicro 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # To use, store as .git/hooks/pre-commit inside your repository and make sure 17 | # it has execute permissions. 18 | # 19 | # This script does not handle file names that contain spaces. 20 | 21 | # Pre-commit configuration 22 | 23 | make check 24 | printf "执行检查中...\n" 25 | 26 | if [ $? -ne 0 ]; then 27 | echo >&2 "[ERROR]: 有文件发生变更,请将变更文件添加到本次提交中" 28 | exit 1 29 | fi 30 | 31 | exit 0 -------------------------------------------------------------------------------- /.github/workflows/license.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Check License Lines 16 | on: 17 | pull_request: 18 | types: [opened, synchronize, reopened, labeled, unlabeled] 19 | branches: 20 | - develop 21 | - main 22 | - dev 23 | jobs: 24 | check-license-lines: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@master 28 | - name: Check License Lines 29 | uses: kt3k/license_checker@v1.0.6 -------------------------------------------------------------------------------- /retry.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package rlock 16 | 17 | import "time" 18 | 19 | type RetryStrategy interface { 20 | // Next 返回下一次重试的间隔,如果不需要继续重试,那么第二参数发挥 false 21 | Next() (time.Duration, bool) 22 | } 23 | 24 | type FixIntervalRetry struct { 25 | // 重试间隔 26 | Interval time.Duration 27 | // 最大次数 28 | Max int 29 | cnt int 30 | } 31 | 32 | func (f *FixIntervalRetry) Next() (time.Duration, bool) { 33 | f.cnt++ 34 | return f.Interval, f.cnt <= f.Max 35 | } 36 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Mark stale issues and pull requests 16 | 17 | on: 18 | schedule: 19 | - cron: "30 1 * * *" 20 | 21 | jobs: 22 | stale: 23 | 24 | runs-on: ubuntu-latest 25 | 26 | steps: 27 | - uses: actions/stale@v4 28 | with: 29 | repo-token: ${{ secrets.GITHUB_TOKEN }} 30 | stale-issue-message: 'This issue is inactive for a long time.' 31 | stale-pr-message: 'This PR is inactive for a long time' 32 | stale-issue-label: 'inactive-issue' 33 | stale-pr-label: 'inactive-pr' 34 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Go 16 | 17 | on: 18 | push: 19 | branches: [ dev ] 20 | pull_request: 21 | branches: [ dev ] 22 | 23 | jobs: 24 | build: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v2 28 | - name: Set up Go 29 | uses: actions/setup-go@v2 30 | with: 31 | go-version: 1.18 32 | 33 | - name: Build 34 | run: go build -v ./... 35 | 36 | - name: Test 37 | run: go test -race -coverprofile=cover.out -v ./... 38 | 39 | - name: Post Coverage 40 | uses: codecov/codecov-action@v2 -------------------------------------------------------------------------------- /.codecov.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | coverage: 16 | status: 17 | project: 18 | default: 19 | # basic 20 | target: 95% 21 | threshold: 0.5% 22 | # advanced settings 23 | branches: 24 | - main 25 | - dev 26 | if_ci_failed: error #success, failure, error, ignore 27 | informational: false 28 | only_pulls: false 29 | patch: 30 | default: 31 | # basic 32 | target: 95% 33 | threshold: 0.5% 34 | branches: 35 | - main 36 | - dev 37 | if_ci_failed: error #success, failure, error, ignore 38 | informational: false 39 | only_pulls: false -------------------------------------------------------------------------------- /.github/workflows/go-fmt.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Format Go code 16 | 17 | on: 18 | push: 19 | branches: [ main,dev ] 20 | pull_request: 21 | branches: [ main,dev ] 22 | 23 | jobs: 24 | build: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v3 28 | - name: Set up Go 29 | uses: actions/setup-go@v3 30 | with: 31 | go-version: ">=1.18.0" 32 | 33 | - name: Install goimports 34 | run: go install golang.org/x/tools/cmd/goimports@latest 35 | 36 | - name: Check 37 | run: | 38 | make check 39 | if [ -n "$(git status --porcelain)" ]; then 40 | echo >&2 "错误: 请在本地运行命令'make check'后再提交." 41 | exit 1 42 | fi -------------------------------------------------------------------------------- /script/setup.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | SOURCE_COMMIT=.github/pre-commit 16 | TARGET_COMMIT=.git/hooks/pre-commit 17 | SOURCE_PUSH=.github/pre-push 18 | TARGET_PUSH=.git/hooks/pre-push 19 | 20 | # copy pre-commit file if not exist. 21 | echo "设置 git pre-commit hooks..." 22 | cp $SOURCE_COMMIT $TARGET_COMMIT 23 | 24 | # copy pre-push file if not exist. 25 | echo "设置 git pre-push hooks..." 26 | cp $SOURCE_PUSH $TARGET_PUSH 27 | 28 | # add permission to TARGET_PUSH and TARGET_COMMIT file. 29 | test -x $TARGET_PUSH || chmod +x $TARGET_PUSH 30 | test -x $TARGET_COMMIT || chmod +x $TARGET_COMMIT 31 | 32 | echo "安装 golangci-lint..." 33 | go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest 34 | 35 | echo "安装 goimports..." 36 | go install golang.org/x/tools/cmd/goimports@latest -------------------------------------------------------------------------------- /.github/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Copyright 2021 gotomicro 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # git test pre-push hook 16 | # 17 | # To use, store as .git/hooks/pre-push inside your repository and make sure 18 | # it has execute permissions. 19 | # 20 | # This script does not handle file names that contain spaces. 21 | 22 | # Pre-push configuration 23 | remote=$1 24 | url=$2 25 | echo >&2 "Try pushing $2 to $1" 26 | 27 | TEST="go test ./... -race -cover -failfast" 28 | LINTER="golangci-lint run" 29 | 30 | # Run test and return if failed 31 | printf "Running go test..." 32 | $TEST 33 | RESULT=$? 34 | if [ $RESULT -ne 0 ]; then 35 | echo >&2 "$TEST" 36 | echo >&2 "Check code to pass test." 37 | exit 1 38 | fi 39 | 40 | # Run linter and return if failed 41 | printf "Running go linter..." 42 | $LINTER 43 | RESULT=$? 44 | if [ $RESULT -ne 0 ]; then 45 | echo >&2 "$LINTER" 46 | echo >&2 "Check code to pass linter." 47 | exit 1 48 | fi 49 | 50 | exit 0 -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 gotomicro 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: golangci-lint 16 | on: 17 | push: 18 | branches: 19 | - dev 20 | - main 21 | pull_request: 22 | branches: 23 | - dev 24 | - main 25 | permissions: 26 | contents: read 27 | # Optional: allow read access to pull request. Use with `only-new-issues` option. 28 | pull-requests: read 29 | jobs: 30 | golangci: 31 | name: lint 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/setup-go@v3 35 | with: 36 | go-version: 1.18 37 | - uses: actions/checkout@v3 38 | - name: golangci-lint 39 | uses: golangci/golangci-lint-action@v3 40 | with: 41 | # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version 42 | version: latest 43 | 44 | # Optional: working directory, useful for monorepos 45 | # working-directory: somedir 46 | 47 | # Optional: golangci-lint command line arguments. 48 | args: -c .golangci.yml 49 | 50 | # Optional: show only new issues if it's a pull request. The default value is `false`. 51 | only-new-issues: true 52 | 53 | # Optional: if set to true then the all caching functionality will be complete disabled, 54 | # takes precedence over all other caching options. 55 | # skip-cache: true 56 | 57 | # Optional: if set to true then the action don't cache or restore ~/go/pkg. 58 | # skip-pkg-cache: true 59 | 60 | # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. 61 | # skip-build-cache: true -------------------------------------------------------------------------------- /demo/demo_e2e_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build demo 16 | 17 | package demo 18 | 19 | import ( 20 | "context" 21 | "testing" 22 | "time" 23 | 24 | "github.com/stretchr/testify/assert" 25 | "github.com/stretchr/testify/require" 26 | ) 27 | 28 | func TestClient_TryLock_e2e(t *testing.T) { 29 | 30 | rdb := redis.NewClient(&redis.Options{ 31 | Addr: "localhost:6379", 32 | Password: "", // no password set 33 | DB: 0, // use default DB 34 | }) 35 | c := NewClient(rdb) 36 | c.Wait() 37 | 38 | testCases := []struct { 39 | name string 40 | 41 | // 准备数据 42 | before func() 43 | // 校验 Redis 数据并且清理数据 44 | after func() 45 | 46 | // 输入 47 | key string 48 | expiration time.Duration 49 | 50 | wantErr error 51 | wantLock *Lock 52 | }{ 53 | { 54 | name: "locked", 55 | before: func() {}, 56 | after: func() { 57 | res, err := rdb.Del(context.Background(), "locked-key").Result() 58 | require.NoError(t, err) 59 | require.Equal(t, int64(1), res) 60 | }, 61 | key: "locked-key", 62 | expiration: time.Minute, 63 | wantLock: &Lock{ 64 | key: "locked-key", 65 | }, 66 | }, 67 | { 68 | name: "failed to lock", 69 | key: "failed-key", 70 | before: func() { 71 | val, err := rdb.Set(context.Background(), "failed-key", "123", time.Minute).Result() 72 | require.NoError(t, err) 73 | require.Equal(t, "OK", val) 74 | }, 75 | after: func() { 76 | res, err := rdb.Get(context.Background(), "failed-key").Result() 77 | require.NoError(t, err) 78 | require.Equal(t, "123", res) 79 | }, 80 | expiration: time.Minute, 81 | wantErr: ErrFailedToPreemptLock, 82 | }, 83 | } 84 | 85 | for _, tc := range testCases { 86 | t.Run(tc.name, func(t *testing.T) { 87 | tc.before() 88 | 89 | l, err := c.TryLock(context.Background(), tc.key, tc.expiration) 90 | assert.Equal(t, tc.wantErr, err) 91 | if err != nil { 92 | return 93 | } 94 | tc.after() 95 | assert.NotNil(t, l.client) 96 | assert.Equal(t, tc.wantLock.key, l.key) 97 | assert.NotEmpty(t, l.value) 98 | }) 99 | } 100 | } 101 | 102 | func (c *Client) Wait() { 103 | for c.client.Ping(context.Background()).Err() != nil { 104 | 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /demo/demo_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build demo 16 | 17 | package demo 18 | 19 | import ( 20 | "context" 21 | "errors" 22 | "testing" 23 | "time" 24 | 25 | "github.com/gotomicro/redis-lock/mocks" 26 | "github.com/redis/go-redis/v9" 27 | "github.com/stretchr/testify/assert" 28 | ) 29 | 30 | func TestClient_TryLock(t *testing.T) { 31 | ctrl := gomock.NewController(t) 32 | defer ctrl.Finish() 33 | testCases := []struct { 34 | name string 35 | 36 | mock func() redis.Cmdable 37 | 38 | // 输入 39 | key string 40 | expiration time.Duration 41 | 42 | wantErr error 43 | wantLock *Lock 44 | }{ 45 | { 46 | name: "locked", 47 | key: "locked-key", 48 | expiration: time.Minute, 49 | mock: func() redis.Cmdable { 50 | rdb := mocks.NewMockCmdable(ctrl) 51 | res := redis.NewBoolResult(true, nil) 52 | rdb.EXPECT(). 53 | SetNX(gomock.Any(), "locked-key", gomock.Any(), time.Minute). 54 | Return(res) 55 | return rdb 56 | }, 57 | wantLock: &Lock{ 58 | key: "locked-key", 59 | }, 60 | }, 61 | 62 | { 63 | name: "network error", 64 | key: "network-key", 65 | expiration: time.Minute, 66 | mock: func() redis.Cmdable { 67 | rdb := mocks.NewMockCmdable(ctrl) 68 | res := redis.NewBoolResult(false, errors.New("network error")) 69 | rdb.EXPECT(). 70 | SetNX(gomock.Any(), "network-key", gomock.Any(), time.Minute). 71 | Return(res) 72 | return rdb 73 | }, 74 | wantErr: errors.New("network error"), 75 | }, 76 | 77 | { 78 | name: "failed to lock", 79 | key: "failed-key", 80 | expiration: time.Minute, 81 | mock: func() redis.Cmdable { 82 | rdb := mocks.NewMockCmdable(ctrl) 83 | res := redis.NewBoolResult(false, nil) 84 | rdb.EXPECT(). 85 | SetNX(gomock.Any(), "failed-key", gomock.Any(), time.Minute). 86 | Return(res) 87 | return rdb 88 | }, 89 | wantErr: ErrFailedToPreemptLock, 90 | }, 91 | } 92 | 93 | for _, tc := range testCases { 94 | t.Run(tc.name, func(t *testing.T) { 95 | c := NewClient(tc.mock()) 96 | l, err := c.TryLock(context.Background(), tc.key, tc.expiration) 97 | assert.Equal(t, tc.wantErr, err) 98 | if err != nil { 99 | return 100 | } 101 | assert.NotNil(t, l.client) 102 | assert.Equal(t, tc.wantLock.key, l.key) 103 | assert.NotEmpty(t, l.value) 104 | }) 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= 2 | github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= 3 | github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= 4 | github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 5 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= 9 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= 10 | github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= 11 | github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= 12 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 13 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 14 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 15 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 16 | github.com/redis/go-redis/v9 v9.3.0 h1:RiVDjmig62jIWp7Kk4XVLs0hzV6pI3PyTnnL0cnn0u0= 17 | github.com/redis/go-redis/v9 v9.3.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= 18 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 19 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 20 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 21 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 22 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 23 | github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= 24 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 25 | github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 26 | go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= 27 | go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= 28 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 29 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 30 | golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 31 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 32 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 33 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= 34 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 35 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 36 | golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0 h1:cu5kTvlzcw1Q5S9f5ip1/cpiB4nXvw1XYzFPGgzLUOY= 37 | golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 38 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 39 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 40 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 41 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 42 | golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 43 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 44 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 45 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 46 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 47 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 48 | golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= 49 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 50 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 51 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 52 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 53 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 54 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 55 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 56 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 57 | -------------------------------------------------------------------------------- /demo/demo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build demo 16 | 17 | package demo 18 | 19 | import ( 20 | "context" 21 | _ "embed" 22 | "errors" 23 | "time" 24 | 25 | rlock "github.com/gotomicro/redis-lock" 26 | "github.com/redis/go-redis/v9" 27 | "golang.org/x/sync/singleflight" 28 | ) 29 | 30 | var ( 31 | ErrLockNotHold = errors.New("未持有锁") 32 | ErrFailedToPreemptLock = errors.New("加锁失败") 33 | //go:embed unlock.lua 34 | luaUnlock string 35 | //go:embed refresh.lua 36 | luaRefresh string 37 | //go:embed lock.lua 38 | luaLock string 39 | ) 40 | 41 | type Client struct { 42 | client redis.Cmdable 43 | s singleflight.Group 44 | } 45 | 46 | func NewClient(c redis.Cmdable) *Client { 47 | return &Client{ 48 | client: c, 49 | } 50 | } 51 | 52 | func (c *Client) SingleflightLock(ctx context.Context, key string, 53 | expiration time.Duration, retry rlock.RetryStrategy, timeout time.Duration) (*Lock, error) { 54 | for { 55 | flag := false 56 | resCh := c.s.DoChan(key, func() (interface{}, error) { 57 | flag = true 58 | return c.Lock(ctx, key, expiration, retry, timeout) 59 | }) 60 | select { 61 | case res := <-resCh: 62 | if flag { 63 | if res.Err != nil { 64 | return nil, res.Err 65 | } 66 | return res.Val.(*Lock), nil 67 | } 68 | case <-ctx.Done(): 69 | return nil, ctx.Err() 70 | } 71 | } 72 | } 73 | 74 | func (c *Client) Lock(ctx context.Context, key string, 75 | expiration time.Duration, retry rlock.RetryStrategy, timeout time.Duration) (*Lock, error) { 76 | value := uuid.New().String() 77 | var timer *time.Timer 78 | defer func() { 79 | if timer != nil { 80 | timer.Stop() 81 | } 82 | }() 83 | for { 84 | lctx, cancel := context.WithTimeout(ctx, timeout) 85 | res, err := c.client.Eval(lctx, luaLock, []string{key}, value, expiration).Bool() 86 | cancel() 87 | 88 | if err != nil && !errors.Is(err, context.DeadlineExceeded) { 89 | return nil, err 90 | } 91 | if res { 92 | return newLock(c.client, key, value, expiration), nil 93 | } 94 | interval, ok := retry.Next() 95 | if !ok { 96 | // 不用重试 97 | return nil, ErrFailedToPreemptLock 98 | } 99 | if timer == nil { 100 | timer = time.NewTimer(interval) 101 | } 102 | timer.Reset(interval) 103 | select { 104 | case <-ctx.Done(): 105 | return nil, ctx.Err() 106 | case <-timer.C: 107 | } 108 | } 109 | } 110 | 111 | // TryLock (ctx, key, time.Second * 10) 112 | func (c *Client) TryLock(ctx context.Context, key string, 113 | expiration time.Duration) (*Lock, error) { 114 | value := uuid.New().String() 115 | res, err := c.client.SetNX(ctx, key, value, expiration).Result() 116 | if err != nil { 117 | return nil, err 118 | } 119 | if !res { 120 | return nil, ErrFailedToPreemptLock 121 | } 122 | return newLock(c.client, key, value, expiration), nil 123 | } 124 | 125 | type Lock struct { 126 | client redis.Cmdable 127 | key string 128 | value string 129 | expiration time.Duration 130 | unlock chan struct{} 131 | } 132 | 133 | func newLock(client redis.Cmdable, key string, value string, expiration time.Duration) *Lock { 134 | return &Lock{ 135 | client: client, 136 | key: key, 137 | value: value, 138 | expiration: expiration, 139 | unlock: make(chan struct{}, 1), 140 | } 141 | } 142 | 143 | func (l *Lock) AutoRefresh(interval time.Duration, timeout time.Duration) error { 144 | ch := make(chan struct{}, 1) 145 | defer close(ch) 146 | ticker := time.NewTicker(interval) 147 | for { 148 | select { 149 | case <-ch: 150 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 151 | err := l.Refresh(ctx) 152 | cancel() 153 | if err == context.DeadlineExceeded { 154 | ch <- struct{}{} 155 | continue 156 | } 157 | if err != nil { 158 | return err 159 | } 160 | case <-ticker.C: 161 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 162 | err := l.Refresh(ctx) 163 | cancel() 164 | if err == context.DeadlineExceeded { 165 | ch <- struct{}{} 166 | continue 167 | } 168 | if err != nil { 169 | return err 170 | } 171 | case <-l.unlock: 172 | return nil 173 | } 174 | } 175 | } 176 | 177 | func (l *Lock) Refresh(ctx context.Context) error { 178 | res, err := l.client.Eval(ctx, luaRefresh, []string{l.key}, l.value, l.expiration.Milliseconds()).Int64() 179 | if err == redis.Nil { 180 | return ErrLockNotHold 181 | } 182 | if err != nil { 183 | return err 184 | } 185 | if res != 1 { 186 | return ErrLockNotHold 187 | } 188 | return nil 189 | } 190 | 191 | func (l *Lock) Unlock(ctx context.Context) error { 192 | defer func() { 193 | l.unlock <- struct{}{} 194 | close(l.unlock) 195 | }() 196 | res, err := l.client.Eval(ctx, luaUnlock, []string{l.key}, l.value).Int64() 197 | 198 | if err == redis.Nil { 199 | return ErrLockNotHold 200 | } 201 | 202 | if err != nil { 203 | return err 204 | } 205 | // 要判断 res 是不是 1 206 | if res == 0 { 207 | // 这把锁不是你的,或者这个 key 不存在 208 | return ErrLockNotHold 209 | } 210 | 211 | return nil 212 | } 213 | -------------------------------------------------------------------------------- /lock.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package rlock 16 | 17 | import ( 18 | "context" 19 | _ "embed" 20 | "errors" 21 | "fmt" 22 | "github.com/redis/go-redis/v9" 23 | "sync" 24 | "time" 25 | 26 | "github.com/google/uuid" 27 | "golang.org/x/sync/singleflight" 28 | ) 29 | 30 | var ( 31 | //go:embed script/lua/unlock.lua 32 | luaUnlock string 33 | //go:embed script/lua/refresh.lua 34 | luaRefresh string 35 | 36 | //go:embed script/lua/lock.lua 37 | luaLock string 38 | 39 | ErrFailedToPreemptLock = errors.New("rlock: 抢锁失败") 40 | // ErrLockNotHold 一般是出现在你预期你本来持有锁,结果却没有持有锁的地方 41 | // 比如说当你尝试释放锁的时候,可能得到这个错误 42 | // 这一般意味着有人绕开了 rlock 的控制,直接操作了 Redis 43 | ErrLockNotHold = errors.New("rlock: 未持有锁") 44 | ) 45 | 46 | type Client struct { 47 | client redis.Cmdable 48 | g singleflight.Group 49 | // valuer 用于生成值,将来可以考虑暴露出去允许用户自定义 50 | valuer func() string 51 | } 52 | 53 | func NewClient(client redis.Cmdable) *Client { 54 | return &Client{ 55 | client: client, 56 | valuer: func() string { 57 | return uuid.New().String() 58 | }, 59 | } 60 | } 61 | 62 | func (c *Client) SingleflightLock(ctx context.Context, key string, expiration time.Duration, retry RetryStrategy, timeout time.Duration) (*Lock, error) { 63 | for { 64 | flag := false 65 | result := c.g.DoChan(key, func() (interface{}, error) { 66 | flag = true 67 | return c.Lock(ctx, key, expiration, retry, timeout) 68 | }) 69 | select { 70 | case res := <-result: 71 | if flag { 72 | c.g.Forget(key) 73 | if res.Err != nil { 74 | return nil, res.Err 75 | } 76 | return res.Val.(*Lock), nil 77 | } 78 | case <-ctx.Done(): 79 | return nil, ctx.Err() 80 | } 81 | } 82 | } 83 | 84 | // Lock 是尽可能重试减少加锁失败的可能 85 | // Lock 会在超时或者锁正被人持有的时候进行重试 86 | // 最后返回的 error 使用 errors.Is 判断,可能是: 87 | // - context.DeadlineExceeded: Lock 整体调用超时 88 | // - ErrFailedToPreemptLock: 超过重试次数,但是整个重试过程都没有出现错误 89 | // - DeadlineExceeded 和 ErrFailedToPreemptLock: 超过重试次数,但是最后一次重试超时了 90 | // 你在使用的过程中,应该注意: 91 | // - 如果 errors.Is(err, context.DeadlineExceeded) 那么最终有没有加锁成功,谁也不知道 92 | // - 如果 errors.Is(err, ErrFailedToPreemptLock) 说明肯定没成功,而且超过了重试次数 93 | // - 否则,和 Redis 通信出了问题 94 | func (c *Client) Lock(ctx context.Context, key string, expiration time.Duration, retry RetryStrategy, timeout time.Duration) (*Lock, error) { 95 | val := c.valuer() 96 | var timer *time.Timer 97 | defer func() { 98 | if timer != nil { 99 | timer.Stop() 100 | } 101 | }() 102 | for { 103 | lctx, cancel := context.WithTimeout(ctx, timeout) 104 | res, err := c.client.Eval(lctx, luaLock, []string{key}, val, expiration.Seconds()).Result() 105 | cancel() 106 | if err != nil && !errors.Is(err, context.DeadlineExceeded) { 107 | // 非超时错误,那么基本上代表遇到了一些不可挽回的场景,所以没太大必要继续尝试了 108 | // 比如说 Redis server 崩了,或者 EOF 了 109 | return nil, err 110 | } 111 | if res == "OK" { 112 | return newLock(c.client, key, val, expiration), nil 113 | } 114 | interval, ok := retry.Next() 115 | if !ok { 116 | if err != nil { 117 | err = fmt.Errorf("最后一次重试错误: %w", err) 118 | } else { 119 | err = fmt.Errorf("锁被人持有: %w", ErrFailedToPreemptLock) 120 | } 121 | return nil, fmt.Errorf("rlock: 重试机会耗尽,%w", err) 122 | } 123 | if timer == nil { 124 | timer = time.NewTimer(interval) 125 | } else { 126 | timer.Reset(interval) 127 | } 128 | select { 129 | case <-timer.C: 130 | case <-ctx.Done(): 131 | return nil, ctx.Err() 132 | } 133 | } 134 | } 135 | 136 | func (c *Client) TryLock(ctx context.Context, 137 | key string, expiration time.Duration) (*Lock, error) { 138 | val := c.valuer() 139 | ok, err := c.client.SetNX(ctx, key, val, expiration).Result() 140 | if err != nil { 141 | // 网络问题,服务器问题,或者超时,都会走过来这里 142 | return nil, err 143 | } 144 | if !ok { 145 | // 已经有人加锁了,或者刚好和人一起加锁,但是自己竞争失败了 146 | return nil, ErrFailedToPreemptLock 147 | } 148 | return newLock(c.client, key, val, expiration), nil 149 | } 150 | 151 | type Lock struct { 152 | client redis.Cmdable 153 | key string 154 | value string 155 | expiration time.Duration 156 | unlock chan struct{} 157 | signalUnlockOnce sync.Once 158 | } 159 | 160 | func newLock(client redis.Cmdable, key string, value string, expiration time.Duration) *Lock { 161 | return &Lock{ 162 | client: client, 163 | key: key, 164 | value: value, 165 | expiration: expiration, 166 | unlock: make(chan struct{}, 1), 167 | } 168 | } 169 | 170 | func (l *Lock) AutoRefresh(interval time.Duration, timeout time.Duration) error { 171 | ticker := time.NewTicker(interval) 172 | // 刷新超时 channel 173 | ch := make(chan struct{}, 1) 174 | defer func() { 175 | ticker.Stop() 176 | close(ch) 177 | }() 178 | for { 179 | select { 180 | case <-ticker.C: 181 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 182 | err := l.Refresh(ctx) 183 | cancel() 184 | // 超时这里,可以继续尝试 185 | if err == context.DeadlineExceeded { 186 | // 因为有两个可能的地方要写入数据,而 ch 187 | // 容量只有一个,所以如果写不进去就说明前一次调用超时了,并且还没被处理, 188 | // 与此同时计时器也触发了 189 | select { 190 | case ch <- struct{}{}: 191 | default: 192 | } 193 | continue 194 | } 195 | if err != nil { 196 | return err 197 | } 198 | case <-ch: 199 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 200 | err := l.Refresh(ctx) 201 | cancel() 202 | // 超时这里,可以继续尝试 203 | if err == context.DeadlineExceeded { 204 | select { 205 | case ch <- struct{}{}: 206 | default: 207 | } 208 | continue 209 | } 210 | if err != nil { 211 | return err 212 | } 213 | case <-l.unlock: 214 | return nil 215 | } 216 | } 217 | } 218 | 219 | func (l *Lock) Refresh(ctx context.Context) error { 220 | res, err := l.client.Eval(ctx, luaRefresh, 221 | []string{l.key}, l.value, l.expiration.Seconds()).Int64() 222 | if err != nil { 223 | return err 224 | } 225 | if res != 1 { 226 | return ErrLockNotHold 227 | } 228 | return nil 229 | } 230 | 231 | // Unlock 解锁 232 | func (l *Lock) Unlock(ctx context.Context) error { 233 | res, err := l.client.Eval(ctx, luaUnlock, []string{l.key}, l.value).Int64() 234 | defer func() { 235 | // 避免重复解锁引起 panic 236 | l.signalUnlockOnce.Do(func() { 237 | l.unlock <- struct{}{} 238 | close(l.unlock) 239 | }) 240 | }() 241 | if err == redis.Nil { 242 | return ErrLockNotHold 243 | } 244 | if err != nil { 245 | return err 246 | } 247 | if res != 1 { 248 | return ErrLockNotHold 249 | } 250 | return nil 251 | } 252 | -------------------------------------------------------------------------------- /lock_e2e_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build e2e 16 | 17 | package rlock 18 | 19 | import ( 20 | "context" 21 | "errors" 22 | "testing" 23 | "time" 24 | 25 | "github.com/stretchr/testify/assert" 26 | "github.com/stretchr/testify/require" 27 | "github.com/stretchr/testify/suite" 28 | ) 29 | 30 | type ClientE2ESuite struct { 31 | suite.Suite 32 | rdb redis.Cmdable 33 | } 34 | 35 | func (s *ClientE2ESuite) SetupSuite() { 36 | s.rdb = redis.NewClient(&redis.Options{ 37 | Addr: "localhost:6379", 38 | Password: "", // no password set 39 | DB: 0, // use default DB 40 | }) 41 | // 确保测试的目标 Redis 已经启动成功了 42 | for s.rdb.Ping(context.Background()).Err() != nil { 43 | 44 | } 45 | } 46 | 47 | func TestClientE2E(t *testing.T) { 48 | suite.Run(t, &ClientE2ESuite{}) 49 | } 50 | 51 | func (s *ClientE2ESuite) TestLock() { 52 | t := s.T() 53 | rdb := s.rdb 54 | testCases := []struct { 55 | name string 56 | 57 | key string 58 | expiration time.Duration 59 | retry RetryStrategy 60 | timeout time.Duration 61 | 62 | client *Client 63 | 64 | wantLock *Lock 65 | wantErr error 66 | 67 | before func() 68 | after func() 69 | }{ 70 | { 71 | // 一次加锁成功 72 | name: "locked", 73 | key: "locked-key", 74 | retry: &FixIntervalRetry{Interval: time.Second, Max: 3}, 75 | timeout: time.Second, 76 | expiration: time.Minute, 77 | client: NewClient(rdb), 78 | before: func() {}, 79 | after: func() { 80 | res, err := rdb.Del(context.Background(), "locked-key").Result() 81 | require.NoError(t, err) 82 | require.Equal(t, int64(1), res) 83 | }, 84 | }, 85 | { 86 | // 加锁不成功 87 | name: "failed", 88 | key: "failed-key", 89 | retry: &FixIntervalRetry{Interval: time.Second, Max: 3}, 90 | timeout: time.Second, 91 | expiration: time.Minute, 92 | client: NewClient(rdb), 93 | before: func() { 94 | res, err := rdb.Set(context.Background(), "failed-key", "123", time.Minute).Result() 95 | require.NoError(t, err) 96 | require.Equal(t, "OK", res) 97 | }, 98 | after: func() { 99 | res, err := rdb.Get(context.Background(), "failed-key").Result() 100 | require.NoError(t, err) 101 | require.Equal(t, "123", res) 102 | delRes, err := rdb.Del(context.Background(), "failed-key").Result() 103 | require.NoError(t, err) 104 | require.Equal(t, int64(1), delRes) 105 | }, 106 | wantErr: context.DeadlineExceeded, 107 | }, 108 | { 109 | // 已经加锁,再加锁就是刷新超时时间 110 | name: "already-locked", 111 | key: "already-key", 112 | retry: &FixIntervalRetry{Interval: time.Second, Max: 3}, 113 | timeout: time.Second, 114 | expiration: time.Minute, 115 | client: func() *Client { 116 | client := NewClient(rdb) 117 | client.valuer = func() string { 118 | return "123" 119 | } 120 | return client 121 | }(), 122 | before: func() { 123 | res, err := rdb.Set(context.Background(), "already-key", "123", time.Minute).Result() 124 | require.NoError(t, err) 125 | require.Equal(t, "OK", res) 126 | }, 127 | after: func() { 128 | res, err := rdb.Get(context.Background(), "already-key").Result() 129 | require.NoError(t, err) 130 | require.Equal(t, "123", res) 131 | delRes, err := rdb.Del(context.Background(), "already-key").Result() 132 | require.NoError(t, err) 133 | require.Equal(t, int64(1), delRes) 134 | }, 135 | }, 136 | } 137 | 138 | for _, tc := range testCases { 139 | t.Run(tc.name, func(t *testing.T) { 140 | tc.before() 141 | l, err := tc.client.Lock(context.Background(), tc.key, tc.expiration, tc.retry, tc.timeout) 142 | assert.True(t, errors.Is(err, tc.wantErr)) 143 | if err != nil { 144 | return 145 | } 146 | assert.Equal(t, tc.key, l.key) 147 | assert.Equal(t, tc.expiration, l.expiration) 148 | assert.NotEmpty(t, l.value) 149 | tc.after() 150 | }) 151 | } 152 | } 153 | 154 | func (s *ClientE2ESuite) TestTryLock() { 155 | t := s.T() 156 | rdb := s.rdb 157 | client := NewClient(rdb) 158 | testCases := []struct { 159 | name string 160 | 161 | key string 162 | expiration time.Duration 163 | 164 | wantLock *Lock 165 | wantErr error 166 | 167 | before func() 168 | after func() 169 | }{ 170 | { 171 | // 加锁成功 172 | name: "locked", 173 | key: "locked-key", 174 | expiration: time.Minute, 175 | before: func() {}, 176 | after: func() { 177 | res, err := rdb.Del(context.Background(), "locked-key").Result() 178 | require.NoError(t, err) 179 | require.Equal(t, int64(1), res) 180 | }, 181 | wantLock: &Lock{ 182 | key: "locked-key", 183 | expiration: time.Minute, 184 | }, 185 | }, 186 | { 187 | // 模拟并发竞争失败 188 | name: "failed", 189 | key: "failed-key", 190 | expiration: time.Minute, 191 | before: func() { 192 | // 假设已经有人设置了分布式锁 193 | val, err := rdb.Set(context.Background(), "failed-key", "123", time.Minute).Result() 194 | require.NoError(t, err) 195 | require.Equal(t, "OK", val) 196 | }, 197 | after: func() { 198 | res, err := rdb.Del(context.Background(), "failed-key").Result() 199 | require.NoError(t, err) 200 | require.Equal(t, int64(1), res) 201 | }, 202 | wantErr: ErrFailedToPreemptLock, 203 | }, 204 | } 205 | 206 | for _, tc := range testCases { 207 | t.Run(tc.name, func(t *testing.T) { 208 | tc.before() 209 | l, err := client.TryLock(context.Background(), tc.key, tc.expiration) 210 | assert.Equal(t, tc.wantErr, err) 211 | if err != nil { 212 | return 213 | } 214 | assert.Equal(t, tc.key, l.key) 215 | assert.Equal(t, tc.expiration, l.expiration) 216 | assert.NotEmpty(t, l.value) 217 | tc.after() 218 | }) 219 | } 220 | } 221 | 222 | func (s *ClientE2ESuite) TestRefresh() { 223 | t := s.T() 224 | rdb := s.rdb 225 | testCases := []struct { 226 | name string 227 | 228 | timeout time.Duration 229 | lock *Lock 230 | 231 | wantErr error 232 | 233 | before func() 234 | after func() 235 | }{ 236 | { 237 | name: "refresh success", 238 | lock: &Lock{ 239 | key: "refresh-key", 240 | value: "123", 241 | expiration: time.Minute, 242 | unlock: make(chan struct{}, 1), 243 | client: rdb, 244 | }, 245 | before: func() { 246 | // 设置一个比较短的过期时间 247 | res, err := rdb.SetNX(context.Background(), 248 | "refresh-key", "123", time.Second*10).Result() 249 | require.NoError(t, err) 250 | assert.True(t, res) 251 | }, 252 | after: func() { 253 | res, err := rdb.TTL(context.Background(), "refresh-key").Result() 254 | require.NoError(t, err) 255 | // 刷新完过期时间 256 | assert.True(t, res.Seconds() > 50) 257 | // 清理数据 258 | rdb.Del(context.Background(), "refresh-key") 259 | }, 260 | timeout: time.Minute, 261 | }, 262 | { 263 | // 锁被人持有 264 | name: "refresh failed", 265 | lock: &Lock{ 266 | key: "refresh-key", 267 | value: "123", 268 | expiration: time.Minute, 269 | unlock: make(chan struct{}, 1), 270 | client: rdb, 271 | }, 272 | before: func() { 273 | // 设置一个比较短的过期时间 274 | res, err := rdb.SetNX(context.Background(), 275 | "refresh-key", "456", time.Second*10).Result() 276 | require.NoError(t, err) 277 | assert.True(t, res) 278 | }, 279 | after: func() { 280 | res, err := rdb.Get(context.Background(), "refresh-key").Result() 281 | require.NoError(t, err) 282 | require.Equal(t, "456", res) 283 | rdb.Del(context.Background(), "refresh-key") 284 | }, 285 | timeout: time.Minute, 286 | wantErr: ErrLockNotHold, 287 | }, 288 | } 289 | 290 | for _, tc := range testCases { 291 | t.Run(tc.name, func(t *testing.T) { 292 | tc.before() 293 | ctx, cancel := context.WithTimeout(context.Background(), tc.timeout) 294 | err := tc.lock.Refresh(ctx) 295 | cancel() 296 | assert.Equal(t, tc.wantErr, err) 297 | tc.after() 298 | }) 299 | } 300 | } 301 | 302 | func (s *ClientE2ESuite) TestAutoRefresh() { 303 | t := s.T() 304 | rdb := s.rdb 305 | client := NewClient(rdb) 306 | l, err := client.TryLock(context.Background(), "auto-refresh-key", time.Second) 307 | require.NoError(t, err) 308 | go func() { 309 | err = l.AutoRefresh(time.Millisecond*800, time.Millisecond*300) 310 | require.NoError(t, err) 311 | }() 312 | // 模拟业务 313 | time.Sleep(time.Second * 2) 314 | // 因为自动刷新了,所以 key 还在 315 | res, err := rdb.Exists(context.Background(), "auto-refresh-key").Result() 316 | require.NoError(t, err) 317 | require.Equal(t, int64(1), res) 318 | 319 | err = l.Unlock(context.Background()) 320 | require.NoError(t, err) 321 | } 322 | 323 | func (s *ClientE2ESuite) TestUnLock() { 324 | t := s.T() 325 | rdb := s.rdb 326 | client := NewClient(rdb) 327 | testCases := []struct { 328 | name string 329 | 330 | lock *Lock 331 | 332 | before func() 333 | after func() 334 | 335 | wantLock *Lock 336 | wantErr error 337 | }{ 338 | { 339 | name: "unlocked", 340 | lock: func() *Lock { 341 | l, err := client.TryLock(context.Background(), "unlocked-key", time.Minute) 342 | require.NoError(t, err) 343 | return l 344 | }(), 345 | before: func() {}, 346 | after: func() { 347 | res, err := rdb.Exists(context.Background(), "unlocked-key").Result() 348 | require.NoError(t, err) 349 | require.Equal(t, 1, res) 350 | }, 351 | }, 352 | { 353 | name: "lock not hold", 354 | lock: newLock(rdb, "not-hold-key", "123", time.Minute), 355 | wantErr: ErrLockNotHold, 356 | }, 357 | } 358 | 359 | for _, tc := range testCases { 360 | t.Run(tc.name, func(t *testing.T) { 361 | err := tc.lock.Unlock(context.Background()) 362 | require.Equal(t, tc.wantErr, err) 363 | }) 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lock_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 gotomicro 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package rlock 16 | 17 | import ( 18 | "context" 19 | "errors" 20 | "fmt" 21 | "go.uber.org/mock/gomock" 22 | "testing" 23 | "time" 24 | 25 | "github.com/gotomicro/redis-lock/mocks" 26 | "github.com/redis/go-redis/v9" 27 | "github.com/stretchr/testify/assert" 28 | "github.com/stretchr/testify/require" 29 | ) 30 | 31 | func TestClient_Lock(t *testing.T) { 32 | t.Parallel() 33 | ctrl := gomock.NewController(t) 34 | defer ctrl.Finish() 35 | testCases := []struct { 36 | name string 37 | 38 | mock func() redis.Cmdable 39 | 40 | key string 41 | expiration time.Duration 42 | retry RetryStrategy 43 | timeout time.Duration 44 | 45 | wantLock *Lock 46 | wantErr string 47 | }{ 48 | { 49 | name: "locked", 50 | mock: func() redis.Cmdable { 51 | cmdable := mocks.NewMockCmdable(ctrl) 52 | res := redis.NewCmd(context.Background(), nil) 53 | res.SetVal("OK") 54 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"locked-key"}, gomock.Any()). 55 | Return(res) 56 | return cmdable 57 | }, 58 | key: "locked-key", 59 | expiration: time.Minute, 60 | retry: &FixIntervalRetry{Interval: time.Second, Max: 1}, 61 | timeout: time.Second, 62 | wantLock: &Lock{ 63 | key: "locked-key", 64 | expiration: time.Minute, 65 | }, 66 | }, 67 | { 68 | name: "not retryable", 69 | mock: func() redis.Cmdable { 70 | cmdable := mocks.NewMockCmdable(ctrl) 71 | res := redis.NewCmd(context.Background(), nil) 72 | res.SetErr(errors.New("network error")) 73 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"locked-key"}, gomock.Any()). 74 | Return(res) 75 | return cmdable 76 | }, 77 | key: "locked-key", 78 | expiration: time.Minute, 79 | retry: &FixIntervalRetry{Interval: time.Second, Max: 1}, 80 | timeout: time.Second, 81 | wantErr: "network error", 82 | }, 83 | { 84 | name: "retry over times", 85 | mock: func() redis.Cmdable { 86 | cmdable := mocks.NewMockCmdable(ctrl) 87 | first := redis.NewCmd(context.Background(), nil) 88 | first.SetErr(context.DeadlineExceeded) 89 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"retry-key"}, gomock.Any()). 90 | Times(3).Return(first) 91 | return cmdable 92 | }, 93 | key: "retry-key", 94 | expiration: time.Minute, 95 | retry: &FixIntervalRetry{Interval: time.Millisecond, Max: 2}, 96 | timeout: time.Second, 97 | wantErr: "rlock: 重试机会耗尽,最后一次重试错误: context deadline exceeded", 98 | }, 99 | { 100 | name: "retry over times-lock holded", 101 | mock: func() redis.Cmdable { 102 | cmdable := mocks.NewMockCmdable(ctrl) 103 | first := redis.NewCmd(context.Background(), nil) 104 | //first.Set 105 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"retry-key"}, gomock.Any()). 106 | Times(3).Return(first) 107 | return cmdable 108 | }, 109 | key: "retry-key", 110 | expiration: time.Minute, 111 | retry: &FixIntervalRetry{Interval: time.Millisecond, Max: 2}, 112 | timeout: time.Second, 113 | wantErr: "rlock: 重试机会耗尽,锁被人持有: rlock: 抢锁失败", 114 | }, 115 | { 116 | name: "retry and success", 117 | mock: func() redis.Cmdable { 118 | cmdable := mocks.NewMockCmdable(ctrl) 119 | first := redis.NewCmd(context.Background(), nil) 120 | first.SetVal("") 121 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"retry-key"}, gomock.Any()). 122 | Times(2).Return(first) 123 | second := redis.NewCmd(context.Background(), nil) 124 | second.SetVal("OK") 125 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"retry-key"}, gomock.Any()). 126 | Return(second) 127 | return cmdable 128 | }, 129 | key: "retry-key", 130 | expiration: time.Minute, 131 | retry: &FixIntervalRetry{Interval: time.Millisecond, Max: 3}, 132 | timeout: time.Second, 133 | wantLock: &Lock{ 134 | key: "retry-key", 135 | expiration: time.Minute, 136 | }, 137 | }, 138 | { 139 | name: "retry but timeout", 140 | mock: func() redis.Cmdable { 141 | cmdable := mocks.NewMockCmdable(ctrl) 142 | first := redis.NewCmd(context.Background(), nil) 143 | first.SetVal("") 144 | cmdable.EXPECT().Eval(gomock.Any(), luaLock, []string{"retry-key"}, gomock.Any()). 145 | Times(2).Return(first) 146 | return cmdable 147 | }, 148 | key: "retry-key", 149 | expiration: time.Minute, 150 | retry: &FixIntervalRetry{Interval: time.Millisecond * 550, Max: 2}, 151 | timeout: time.Second, 152 | wantErr: "context deadline exceeded", 153 | }, 154 | } 155 | 156 | for _, tc := range testCases { 157 | t.Run(tc.name, func(t *testing.T) { 158 | mockRedisCmd := tc.mock() 159 | client := NewClient(mockRedisCmd) 160 | ctx, cancel := context.WithTimeout(context.Background(), tc.timeout) 161 | defer cancel() 162 | l, err := client.Lock(ctx, tc.key, tc.expiration, tc.retry, time.Second) 163 | if tc.wantErr != "" { 164 | assert.EqualError(t, err, tc.wantErr) 165 | return 166 | } else { 167 | require.NoError(t, err) 168 | } 169 | 170 | assert.Equal(t, mockRedisCmd, l.client) 171 | assert.Equal(t, tc.key, l.key) 172 | assert.Equal(t, tc.expiration, l.expiration) 173 | assert.NotEmpty(t, l.value) 174 | }) 175 | } 176 | } 177 | 178 | func TestClient_TryLock(t *testing.T) { 179 | ctrl := gomock.NewController(t) 180 | defer ctrl.Finish() 181 | testCases := []struct { 182 | name string 183 | 184 | mock func() redis.Cmdable 185 | 186 | key string 187 | expiration time.Duration 188 | 189 | wantLock *Lock 190 | wantErr error 191 | }{ 192 | { 193 | // 加锁成功 194 | name: "locked", 195 | key: "locked-key", 196 | expiration: time.Minute, 197 | mock: func() redis.Cmdable { 198 | res := mocks.NewMockCmdable(ctrl) 199 | res.EXPECT().SetNX(gomock.Any(), "locked-key", gomock.Any(), time.Minute). 200 | Return(redis.NewBoolResult(true, nil)) 201 | return res 202 | }, 203 | wantLock: &Lock{ 204 | key: "locked-key", 205 | expiration: time.Minute, 206 | }, 207 | }, 208 | { 209 | // mock 网络错误 210 | name: "network error", 211 | key: "network-key", 212 | expiration: time.Minute, 213 | mock: func() redis.Cmdable { 214 | res := mocks.NewMockCmdable(ctrl) 215 | res.EXPECT().SetNX(gomock.Any(), "network-key", gomock.Any(), time.Minute). 216 | Return(redis.NewBoolResult(false, errors.New("network error"))) 217 | return res 218 | }, 219 | wantErr: errors.New("network error"), 220 | }, 221 | { 222 | // 模拟并发竞争失败 223 | name: "failed", 224 | key: "failed-key", 225 | expiration: time.Minute, 226 | mock: func() redis.Cmdable { 227 | res := mocks.NewMockCmdable(ctrl) 228 | res.EXPECT().SetNX(gomock.Any(), "failed-key", gomock.Any(), time.Minute). 229 | Return(redis.NewBoolResult(false, nil)) 230 | return res 231 | }, 232 | wantErr: ErrFailedToPreemptLock, 233 | }, 234 | } 235 | 236 | for _, tc := range testCases { 237 | t.Run(tc.name, func(t *testing.T) { 238 | mockRedisCmd := tc.mock() 239 | client := NewClient(mockRedisCmd) 240 | l, err := client.TryLock(context.Background(), tc.key, tc.expiration) 241 | assert.Equal(t, tc.wantErr, err) 242 | if err != nil { 243 | return 244 | } 245 | assert.Equal(t, mockRedisCmd, l.client) 246 | assert.Equal(t, tc.key, l.key) 247 | assert.Equal(t, tc.expiration, l.expiration) 248 | assert.NotEmpty(t, l.value) 249 | }) 250 | } 251 | } 252 | 253 | func TestLock_Unlock(t *testing.T) { 254 | ctrl := gomock.NewController(t) 255 | defer ctrl.Finish() 256 | testCases := []struct { 257 | name string 258 | mock func() redis.Cmdable 259 | 260 | wantErr error 261 | }{ 262 | { 263 | // 解锁成功 264 | name: "unlocked", 265 | mock: func() redis.Cmdable { 266 | rdb := mocks.NewMockCmdable(ctrl) 267 | cmd := redis.NewCmd(context.Background()) 268 | cmd.SetVal(int64(1)) 269 | rdb.EXPECT().Eval(gomock.Any(), luaUnlock, gomock.Any(), gomock.Any()). 270 | Return(cmd) 271 | return rdb 272 | }, 273 | }, 274 | { 275 | // 解锁失败,因为网络问题 276 | name: "network error", 277 | mock: func() redis.Cmdable { 278 | rdb := mocks.NewMockCmdable(ctrl) 279 | cmd := redis.NewCmd(context.Background()) 280 | cmd.SetErr(errors.New("network error")) 281 | rdb.EXPECT().Eval(gomock.Any(), luaUnlock, gomock.Any(), gomock.Any()). 282 | Return(cmd) 283 | return rdb 284 | }, 285 | wantErr: errors.New("network error"), 286 | }, 287 | { 288 | // 解锁失败,锁已经过期,或者被人删了 289 | // 或者是别人的锁 290 | name: "lock not exist", 291 | mock: func() redis.Cmdable { 292 | rdb := mocks.NewMockCmdable(ctrl) 293 | cmd := redis.NewCmd(context.Background()) 294 | cmd.SetVal(int64(0)) 295 | rdb.EXPECT().Eval(gomock.Any(), luaUnlock, gomock.Any(), gomock.Any()). 296 | Return(cmd) 297 | return rdb 298 | }, 299 | wantErr: ErrLockNotHold, 300 | }, 301 | } 302 | 303 | for _, tc := range testCases { 304 | t.Run(tc.name, func(t *testing.T) { 305 | l := newLock(tc.mock(), "mock-key", "mock value", time.Minute) 306 | err := l.Unlock(context.Background()) 307 | require.Equal(t, tc.wantErr, err) 308 | }) 309 | } 310 | } 311 | 312 | func ExampleLock_Refresh() { 313 | var lock *Lock 314 | end := make(chan struct{}, 1) 315 | go func() { 316 | ticker := time.NewTicker(time.Second * 30) 317 | for { 318 | select { 319 | case <-ticker.C: 320 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) 321 | err := lock.Refresh(ctx) 322 | cancel() 323 | // 错误处理 324 | 325 | if err == context.DeadlineExceeded { 326 | // 超时,按照道理来说,你应该立刻重试 327 | // 超时之下可能续约成功了,也可能没成功 328 | } 329 | if err != nil { 330 | // 其它错误,你要考虑这个错误能不能继续处理 331 | // 如果不能处理,你怎么通知后续业务中断? 332 | } 333 | case <-end: 334 | // 你的业务退出了 335 | } 336 | } 337 | }() 338 | // 后面是你的业务 339 | fmt.Println("Finish") 340 | // 你的业务完成了 341 | end <- struct{}{} 342 | // Output: 343 | // Finish 344 | } 345 | 346 | func TestClient_SingleflightLock(t *testing.T) { 347 | ctrl := gomock.NewController(t) 348 | defer ctrl.Finish() 349 | rdb := mocks.NewMockCmdable(ctrl) 350 | cmd := redis.NewCmd(context.Background()) 351 | cmd.SetVal("OK") 352 | rdb.EXPECT().Eval(gomock.Any(), luaLock, gomock.Any(), gomock.Any()). 353 | Return(cmd) 354 | client := NewClient(rdb) 355 | // TODO 并发测试 356 | _, err := client.SingleflightLock(context.Background(), 357 | "key1", 358 | time.Minute, 359 | &FixIntervalRetry{ 360 | Interval: time.Millisecond, 361 | Max: 3, 362 | }, time.Second) 363 | require.NoError(t, err) 364 | } 365 | 366 | func TestLock_AutoRefresh(t *testing.T) { 367 | t.Parallel() 368 | ctrl := gomock.NewController(t) 369 | defer ctrl.Finish() 370 | testCases := []struct { 371 | name string 372 | unlockTiming time.Duration 373 | lock func() *Lock 374 | interval time.Duration 375 | timeout time.Duration 376 | wantErr error 377 | }{ 378 | { 379 | name: "auto refresh success", 380 | interval: time.Millisecond * 100, 381 | unlockTiming: time.Second, 382 | timeout: time.Second * 2, 383 | lock: func() *Lock { 384 | rdb := mocks.NewMockCmdable(ctrl) 385 | res := redis.NewCmd(context.Background(), nil) 386 | res.SetVal(int64(1)) 387 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"auto-refreshed"}, []any{"123", float64(60)}). 388 | AnyTimes().Return(res) 389 | cmd := redis.NewCmd(context.Background()) 390 | cmd.SetVal(int64(1)) 391 | rdb.EXPECT().Eval(gomock.Any(), luaUnlock, gomock.Any(), gomock.Any()). 392 | Return(cmd) 393 | return &Lock{ 394 | client: rdb, 395 | key: "auto-refreshed", 396 | value: "123", 397 | expiration: time.Minute, 398 | unlock: make(chan struct{}, 1), 399 | } 400 | }, 401 | }, 402 | { 403 | name: "auto refresh failed", 404 | interval: time.Millisecond * 100, 405 | unlockTiming: time.Second, 406 | timeout: time.Second * 2, 407 | lock: func() *Lock { 408 | rdb := mocks.NewMockCmdable(ctrl) 409 | res := redis.NewCmd(context.Background(), nil) 410 | res.SetErr(errors.New("network error")) 411 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"auto-refreshed"}, []any{"123", float64(60)}). 412 | AnyTimes().Return(res) 413 | cmd := redis.NewCmd(context.Background()) 414 | cmd.SetVal(int64(1)) 415 | rdb.EXPECT().Eval(gomock.Any(), luaUnlock, gomock.Any(), gomock.Any()). 416 | Return(cmd) 417 | return &Lock{ 418 | client: rdb, 419 | key: "auto-refreshed", 420 | value: "123", 421 | expiration: time.Minute, 422 | unlock: make(chan struct{}, 1), 423 | } 424 | }, 425 | wantErr: errors.New("network error"), 426 | }, 427 | { 428 | name: "auto refresh timeout", 429 | interval: time.Millisecond * 100, 430 | unlockTiming: time.Second * 1, 431 | timeout: time.Second * 2, 432 | lock: func() *Lock { 433 | rdb := mocks.NewMockCmdable(ctrl) 434 | first := redis.NewCmd(context.Background(), nil) 435 | first.SetErr(context.DeadlineExceeded) 436 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"auto-refreshed"}, []any{"123", float64(60)}).Return(first) 437 | 438 | second := redis.NewCmd(context.Background(), nil) 439 | second.SetVal(int64(1)) 440 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"auto-refreshed"}, []any{"123", float64(60)}).AnyTimes().Return(first) 441 | 442 | cmd := redis.NewCmd(context.Background()) 443 | cmd.SetVal(int64(1)) 444 | rdb.EXPECT().Eval(gomock.Any(), luaUnlock, gomock.Any(), gomock.Any()). 445 | Return(cmd) 446 | 447 | return &Lock{ 448 | client: rdb, 449 | key: "auto-refreshed", 450 | value: "123", 451 | expiration: time.Minute, 452 | unlock: make(chan struct{}, 1), 453 | } 454 | }, 455 | wantErr: nil, 456 | }, 457 | } 458 | 459 | for _, tt := range testCases { 460 | tc := tt 461 | t.Run(tc.name, func(t *testing.T) { 462 | lock := tc.lock() 463 | go func() { 464 | time.Sleep(tc.unlockTiming) 465 | err := lock.Unlock(context.Background()) 466 | require.NoError(t, err) 467 | }() 468 | err := lock.AutoRefresh(tc.interval, tc.timeout) 469 | assert.Equal(t, tc.wantErr, err) 470 | }) 471 | } 472 | } 473 | 474 | func TestLock_Refresh(t *testing.T) { 475 | ctrl := gomock.NewController(t) 476 | defer ctrl.Finish() 477 | testCases := []struct { 478 | name string 479 | lock func() *Lock 480 | wantErr error 481 | }{ 482 | { 483 | // 续约成功 484 | name: "refreshed", 485 | lock: func() *Lock { 486 | rdb := mocks.NewMockCmdable(ctrl) 487 | res := redis.NewCmd(context.Background(), nil) 488 | res.SetVal(int64(1)) 489 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"refreshed"}, []any{"123", float64(60)}).Return(res) 490 | return &Lock{ 491 | client: rdb, 492 | expiration: time.Minute, 493 | value: "123", 494 | key: "refreshed", 495 | } 496 | }, 497 | }, 498 | { 499 | // 刷新失败 500 | name: "lock not hold", 501 | lock: func() *Lock { 502 | rdb := mocks.NewMockCmdable(ctrl) 503 | res := redis.NewCmd(context.Background(), nil) 504 | res.SetErr(redis.Nil) 505 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"refreshed"}, []any{"123", float64(60)}).Return(res) 506 | return &Lock{ 507 | client: rdb, 508 | expiration: time.Minute, 509 | value: "123", 510 | key: "refreshed", 511 | } 512 | }, 513 | wantErr: redis.Nil, 514 | }, 515 | { 516 | // 未持有锁 517 | name: "lock not hold", 518 | lock: func() *Lock { 519 | rdb := mocks.NewMockCmdable(ctrl) 520 | res := redis.NewCmd(context.Background(), nil) 521 | res.SetVal(int64(0)) 522 | rdb.EXPECT().Eval(gomock.Any(), luaRefresh, []string{"refreshed"}, []any{"123", float64(60)}).Return(res) 523 | return &Lock{ 524 | client: rdb, 525 | expiration: time.Minute, 526 | value: "123", 527 | key: "refreshed", 528 | } 529 | }, 530 | wantErr: ErrLockNotHold, 531 | }, 532 | } 533 | 534 | for _, tc := range testCases { 535 | t.Run(tc.name, func(t *testing.T) { 536 | err := tc.lock().Refresh(context.Background()) 537 | assert.Equal(t, tc.wantErr, err) 538 | }) 539 | } 540 | } 541 | --------------------------------------------------------------------------------