diff --git a/alias.go b/alias.go index bff35fe611e5caaf9e73a56ee7812f64f4d56318..93b2345432117437f651f40ecd88a36d79cd495c 100644 --- a/alias.go +++ b/alias.go @@ -18,6 +18,17 @@ package redis import "gitee.com/go-libs/redis/src" type ( - LockedResource = src.LockedResource - Locker = src.Locker + // Locker + // is an alias for src.Locker. + Locker = src.Locker +) + +var ( + // Connector + // is an alias for src.Connector. + Connector = src.Connector + + // Lock + // is an alias for src.Lock used to obtain a distributed resource lock. + Lock = src.Lock ) diff --git a/config/app.yaml b/config/app.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6900bd2a7452fe619a3cf0410db4026a2a68392b --- /dev/null +++ b/config/app.yaml @@ -0,0 +1,4 @@ +name: "go-libs-redis" +version: "1.0.0" +host: "" +port: 8080 diff --git a/config/log.yaml b/config/log.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d330693959db80cf6d4f0ceadb4f32b226c5aee8 --- /dev/null +++ b/config/log.yaml @@ -0,0 +1,10 @@ +level: debug +time-format: "2006-01-02T15:04:05.999999999Z07:00" +adapter: term +term-adapter: + color: true +tracer: "" +jaeger-tracer: + endpoint: http://localhost:14268/api/traces + username: + password: diff --git a/config/redis.yaml b/config/redis.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d9fd05633088354ff2691dd577eb8a638c93e06 --- /dev/null +++ b/config/redis.yaml @@ -0,0 +1,17 @@ +# Server info. +host: 127.0.0.1 +port: 6379 +password: +database: 0 + +# Pool info. +max-active: 10 +max-lifetime: 60 +min-idle: 1 + +# Timeout. +dial-timeout: 5 +read-timeout: 3 +write-timeout: 3 + +log-command: true \ No newline at end of file diff --git a/go.mod b/go.mod index 6f7e16fc8f80634d801486dbdb3dbe132ad63d86..a56d42f78a74aa3c69dd2dc11c40bea21cf1b3ca 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,38 @@ module gitee.com/go-libs/redis go 1.18 + +require ( + gitee.com/go-libs/config v1.0.1 + gitee.com/go-wares/log v0.1.10 + github.com/go-redis/redis/v8 v8.11.5 +) + +require ( + github.com/IBM/sarama v1.43.1 // indirect + github.com/andybalholm/brotli v1.1.0 // indirect + github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/eapache/go-resiliency v1.6.0 // indirect + github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect + github.com/eapache/queue v1.1.0 // indirect + github.com/elastic/go-elasticsearch/v7 v7.17.10 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/jcmturner/aescts/v2 v2.0.0 // indirect + github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect + github.com/jcmturner/gofork v1.7.6 // indirect + github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect + github.com/jcmturner/rpc/v2 v2.0.3 // indirect + github.com/klauspost/compress v1.17.7 // indirect + github.com/pierrec/lz4/v4 v4.1.21 // indirect + github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasthttp v1.52.0 // indirect + golang.org/x/crypto v0.21.0 // indirect + golang.org/x/net v0.22.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..2f26fc7e29726743ddfbbdd3266a4122e9deaa9a --- /dev/null +++ b/go.sum @@ -0,0 +1,121 @@ +gitee.com/go-libs/config v1.0.1 h1:9q+pfk7g9xX/t87foZ81inNcyysDLCBqhbX78mh76vA= +gitee.com/go-libs/config v1.0.1/go.mod h1:azzGgnpQ4cTP7EXl7uctzfZ0L+y+v7JGYf65qfSwsXs= +gitee.com/go-wares/log v0.1.10 h1:DGvvH6DOF8YXLcBTqABGGhkrwe+OhmD3sV9W6NHcB4E= +gitee.com/go-wares/log v0.1.10/go.mod h1:HDs8rnqgyYDGzrUM+SNJx6/R1MK7JpKG5jqAY1HIW/o= +github.com/IBM/sarama v1.43.1 h1:Z5uz65Px7f4DhI/jQqEm/tV9t8aU+JUdTyW/K/fCXpA= +github.com/IBM/sarama v1.43.1/go.mod h1:GG5q1RURtDNPz8xxJs3mgX6Ytak8Z9eLhAkJPObe2xE= +github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= +github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= +github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= +github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30= +github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3/go.mod h1:YvSRo5mw33fLEx1+DlK6L2VV43tJt5Eyel9n9XBcR+0= +github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/elastic/go-elasticsearch/v7 v7.17.10 h1:TCQ8i4PmIJuBunvBS6bwT2ybzVFxxUhhltAs3Gyu1yo= +github.com/elastic/go-elasticsearch/v7 v7.17.10/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= +github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= +github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= +github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg= +github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= +github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= +github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.52.0 h1:wqBQpxH71XW0e2g+Og4dzQM8pk34aFYlA1Ga8db7gU0= +github.com/valyala/fasthttp v1.52.0/go.mod h1:hf5C4QnVMkNXMspnsUlfM3WitlgYflyhHYoKol/szxQ= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= +golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/src/config.go b/src/config.go new file mode 100644 index 0000000000000000000000000000000000000000..5faf80ecd80d356c5ed2ea82be1ccb75dbac6002 --- /dev/null +++ b/src/config.go @@ -0,0 +1,86 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: wsfuyibing <682805@qq.com> +// Date: 2024-07-17 + +package src + +var configFiles = []string{"redis.yml", "redis.yaml"} + +const ( + DefaultHost = "127.0.0.1" + DefaultNetwork = "tcp" + DefaultPort = 6379 + DefaultMaxActive = 10 + DefaultMinIdle = 2 + DefaultMaxLifetime = 60 + DefaultTimeoutDial = 5 + DefaultTimeoutRead = 3 + DefaultTimeoutWrite = 3 +) + +// Config +// is a component used to parse configurations. +type Config struct { + Network string `yaml:"network"` + Host string `yaml:"host"` + Port int `yaml:"port"` + Password string `yaml:"password"` + Database int `yaml:"database"` + + MaxActive int `yaml:"max-active"` + MaxLifetime int `yaml:"max-lifetime"` + MinIdle int `yaml:"min-idle"` + + DialTimeout int `yaml:"dial-timeout"` + ReadTimeout int `yaml:"read-timeout"` + WriteTimeout int `yaml:"write-timeout"` +} + +// After +// is an event handler that called by config.Resource, Do not call directly. +func (o *Config) After() (err error) { + if o.Host == "" { + o.Host = DefaultHost + } + if o.Network == "" { + o.Network = DefaultNetwork + } + if o.Port == 0 { + o.Port = DefaultPort + } + + // Pool. + if o.MaxActive == 0 { + o.MaxActive = DefaultMaxActive + } + if o.MinIdle == 0 { + o.MinIdle = DefaultMinIdle + } + if o.MaxLifetime == 0 { + o.MaxLifetime = DefaultMaxLifetime + } + + // Timeout. + if o.DialTimeout == 0 { + o.DialTimeout = DefaultTimeoutDial + } + if o.ReadTimeout == 0 { + o.ReadTimeout = DefaultTimeoutRead + } + if o.WriteTimeout == 0 { + o.WriteTimeout = DefaultTimeoutWrite + } + + return +} diff --git a/src/connector.go b/src/connector.go new file mode 100644 index 0000000000000000000000000000000000000000..0c48ce8aa890edc1aafdf1c58fcc10ccfd23b262 --- /dev/null +++ b/src/connector.go @@ -0,0 +1,175 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: wsfuyibing <682805@qq.com> +// Date: 2024-07-17 + +package src + +import ( + "context" + "errors" + "fmt" + "gitee.com/go-libs/config" + "gitee.com/go-wares/log" + gr "github.com/go-redis/redis/v8" + "time" +) + +// Connector +// is a singleton instance used to manage redis connection. +var Connector ConnectorManager + +// Alias for redis/v8 types. + +type ( + Client = gr.Client + Connection = gr.Conn + Cmd = gr.Cmd +) + +type ( + // ConnectorManager + // is an interface used to manage redis connection. + ConnectorManager interface { + // Do + // send a command directly. + Do(ctx context.Context, args ...any) (*Cmd, error) + + // GetClient + // returns a redis client. + GetClient() (client *Client, err error) + + // GetConfig + // returns a config component. + GetConfig() *Config + + // GetConnection + // acquire a redis connection from pool. + GetConnection(ctx context.Context) (connection *Connection, err error) + + // GetError + // returns a error on connector. + GetError() error + } + + connector struct { + client *gr.Client + config *Config + configFile config.Resource + err error + } +) + +func (o *connector) Do(ctx context.Context, args ...any) (cmd *Cmd, err error) { + if err = o.err; err != nil { + log.Errorfc(ctx, `[redis] failed to do: args=%v, error="%v"`, args, err) + return + } + + // Send command. + cmd = o.client.Do(ctx, args...) + + if err = cmd.Err(); errors.Is(err, gr.Nil) { + err = nil + } + + if err != nil { + log.Errorfc(ctx, `[redis] failed to do: args=%v, error="%v"`, args, err) + } else { + log.Infofc(ctx, `[redis] succeed to do: args=%v`, args) + } + return +} + +func (o *connector) GetClient() (client *Client, err error) { + if err = o.err; err == nil { + client = o.client + } + return +} + +func (o *connector) GetConfig() *Config { + return o.config +} + +func (o *connector) GetConnection(ctx context.Context) (connection *Connection, err error) { + if err = o.err; err == nil { + connection = o.client.Conn(ctx) + } + return +} + +func (o *connector) GetError() error { + return o.err +} + +func (o *connector) build() { + // Required options. + opt := &gr.Options{ + Network: o.config.Network, + Addr: fmt.Sprintf(`%s:%d`, o.config.Host, o.config.Port), + Password: o.config.Password, + DB: o.config.Database, + } + + // Optional options. + opt.OnConnect = func(ctx context.Context, _ *Connection) error { + log.Infofc(ctx, "[redis] connect to %s://%s:%d", o.config.Network, o.config.Host, o.config.Port) + return nil + } + + if o.config.MaxActive > 0 { + opt.PoolSize = o.config.MaxActive + } + + if o.config.MinIdle > 0 { + opt.MinIdleConns = o.config.MinIdle + } + + if o.config.MaxLifetime > 0 { + opt.IdleTimeout = time.Duration(o.config.MaxLifetime) * time.Second + } + + // Dial timeout. + // Default: 5 seconds. + if o.config.DialTimeout > 0 { + opt.DialTimeout = time.Duration(o.config.DialTimeout) * time.Second + } + + // Read timeout. + // Default: 3 seconds. + if o.config.ReadTimeout > 0 { + opt.ReadTimeout = time.Duration(o.config.ReadTimeout) * time.Second + } + + // Write timeout. + // Default: 3 seconds. + if o.config.WriteTimeout > 0 { + opt.WriteTimeout = time.Duration(o.config.WriteTimeout) * time.Second + } + + // Build. + o.client = gr.NewClient(opt) +} + +func (o *connector) init() *connector { + o.config = &Config{} + o.configFile = config.Seek(configFiles...) + + // Scan + // config fields from file resource then build connection pool. + if o.err = o.configFile.ScanYaml(o.config); o.err == nil { + o.build() + } + return o +} diff --git a/src/init.go b/src/init.go new file mode 100644 index 0000000000000000000000000000000000000000..8bf71c89c607ae9071eb33bdd218e7b396a5e7b9 --- /dev/null +++ b/src/init.go @@ -0,0 +1,28 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: wsfuyibing <682805@qq.com> +// Date: 2024-07-17 + +package src + +import "sync" + +var ( + once = new(sync.Once) +) + +func init() { + once.Do(func() { + Connector = (&connector{}).init() + }) +} diff --git a/src/lock.go b/src/lock.go index 794d07f6d51af97bf884615cb97727a05ddfa098..13482de5ac6198564a0a407f0bf4d87a69627b16 100644 --- a/src/lock.go +++ b/src/lock.go @@ -15,10 +15,71 @@ package src -type ( - Locker interface { +import ( + "context" + "fmt" + "gitee.com/go-wares/log" + gr "github.com/go-redis/redis/v8" + "math/rand" + "time" +) + +const ( + DefaultLockDuration = time.Second * 60 + DefaultLockRenew = 25 + DefaultLockPrefix = "__LOCKER__" +) + +// Lock +// apply a distributed lock resource. Return nil if given key applied by other connection. +func Lock(ctx context.Context, key string, timeouts ...int) (Locker, error) { + var ( + cmd *gr.BoolCmd + err error + res = &locker{ + ctx: ctx, + duration: DefaultLockDuration, + key: fmt.Sprintf(`%s:%s`, DefaultLockPrefix, key), + } + yes bool + ) + + // Acquire + // a connection from redis pool. + if res.connection, err = Connector.GetConnection(ctx); err != nil { + log.Errorfc(ctx, `[redis][lock] failed to apply for distributed lock: key="%s", error="%v"`, res.key, err) + return nil, err } - LockedResource interface { + // Override default duration. + if len(timeouts) > 0 && timeouts[0] > 0 { + res.duration = time.Duration(timeouts[0]) * time.Second } -) + + // Build a random integer value for distributed lock resource. + res.value = rand.Int31() + + // Send redis command. + cmd = res.connection.SetNX(ctx, res.key, res.value, res.duration) + + // Compare bool result. + if yes, err = cmd.Result(); err != nil { + log.Errorfc(ctx, `[redis][lock] failed to apply for distributed lock: key="%s", error="%v"`, res.key, err) + return nil, err + } + + // Succeed to apply. + if yes { + log.Infofc(ctx, `[redis][lock] succeed to apply for distributed lock: key="%s", value="%v", timeout="%vs"`, res.key, res.value, res.duration.Seconds()) + return res, nil + } + + // Failed to apply for exists, It's applied by other goroutine. + log.Infofc(ctx, `[redis][lock] failed to apply for distributed lock: key="%s", error="exists"`, res.key) + + // Close acquired connection if failed to apply. + if err = res.connection.Close(); err != nil { + log.Warnfc(ctx, `[redis][lock] failed to close connection: key="%s", error="%v"`, res.key, err) + } + return nil, nil +} diff --git a/src/lock_test.go b/src/lock_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a7266b98b95b09a90b501426d66d001ee6adcd4b --- /dev/null +++ b/src/lock_test.go @@ -0,0 +1,49 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: wsfuyibing <682805@qq.com> +// Date: 2024-07-18 + +package src + +import ( + "context" + "testing" + "time" +) + +func TestLock(t *testing.T) { + ExampleLock() +} + +func ExampleLock() { + ctx := context.Background() + key := "key" + + // Apply distributed lock resource. + res, err := Lock(ctx, key) + if err != nil { + return + } + + // Apply failed, It's applied by other goroutine. + if res == nil { + return + } + + // Release applied distributed lock resource when done. + defer res.Release() + res.Renew() + + // Your logic code ... + time.Sleep(time.Second * 3) +} diff --git a/src/locker.go b/src/locker.go new file mode 100644 index 0000000000000000000000000000000000000000..559927bce29c4fcb53cd53983361d90fc5be0cdb --- /dev/null +++ b/src/locker.go @@ -0,0 +1,151 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: wsfuyibing <682805@qq.com> +// Date: 2024-07-17 + +package src + +import ( + "context" + "gitee.com/go-wares/log" + "sync/atomic" + "time" +) + +type ( + // Locker + // is an interface of locker. + Locker interface { + // Release + // applied resource. + Release() + + // Renew + // prevent distributed lock from being deleted due to timeout. + Renew(seconds ...int) + } + + locker struct { + connection *Connection + ctx context.Context + key string + duration time.Duration + value int32 + + renewCanceller context.CancelFunc + renewCalls, renewRunning, renewUpdates int32 + } +) + +func (o *locker) Release() { + // Stops renew goroutine. + if o.renewCanceller != nil { + o.renewCanceller() + + // Wait previous renew done. + for { + if atomic.LoadInt32(&o.renewRunning) == 0 { + break + } + time.Sleep(time.Millisecond) + } + } + + // Delete + // locked resource. + if del := o.connection.Del(o.ctx, o.key); del != nil { + if log.Config().DebugOn() { + affect, _ := del.Uint64() + log.Debugfc(o.ctx, `[redis][lock] succeed to delete distributed lock: key="%s", affect="%d"`, o.key, affect) + } + } + + // Close connection. + if err := o.connection.Close(); err != nil { + if log.Config().DebugOn() { + log.Debugfc(o.ctx, `[redis][lock] failed to close connection`) + } + } else { + if log.Config().DebugOn() { + log.Debugfc(o.ctx, `[redis][lock] succeed to close connection`) + } + } +} + +func (o *locker) Renew(seconds ...int) { + if n := atomic.AddInt32(&o.renewCalls, 1); n > 1 { + atomic.AddInt32(&o.renewCalls, -1) + return + } + if o.ctx != nil { + go o.renew(seconds...) + } +} + +func (o *locker) Update() { + // Update total counter. + count := atomic.AddInt32(&o.renewUpdates, 1) + + // Update running counter. + atomic.AddInt32(&o.renewRunning, 1) + defer atomic.AddInt32(&o.renewRunning, -1) + + // Send command. + cmd := o.connection.Expire(o.ctx, o.key, o.duration) + yes, err := cmd.Result() + if err != nil { + log.Errorfc(o.ctx, `[redis][lock] failed to renew: key="%s", error="%v"`, o.key, err) + } else if log.Config().DebugOn() { + log.Debugfc(o.ctx, `[redis][lock] renew completed: count="%d", succeed="%v"`, count, yes) + } +} + +func (o *locker) renew(seconds ...int) { + var ( + ctx context.Context + frequency = DefaultLockRenew + tick *time.Ticker + ) + + // Generate + // frequency seconds. + if len(seconds) > 0 && seconds[0] > 0 { + frequency = seconds[0] + } + if log.Config().DebugOn() { + log.Debugfc(o.ctx, `[redis][lock] renew started: frequency="%ds"`, frequency) + } + + // Create + // runtime fields. + ctx, o.renewCanceller = context.WithCancel(o.ctx) + tick = time.NewTicker(time.Duration(frequency) * time.Second) + + // Loop + // channel messages. + for { + select { + case <-tick.C: + go o.Update() + + case <-ctx.Done(): + { + tick.Stop() + if log.Config().DebugOn() { + log.Debugfc(o.ctx, `[redis][lock] renew stopped`) + } + } + return + } + } +}