加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 2.21 KB
一键复制 编辑 原始数据 按行查看 历史
phil.wang 提交于 2019-08-17 20:57 . add signal
package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-redis/redis"
//"github.com/spf13/viper"
)
const redisKey = "redis"
// NewExampleClient creates a redis client and ping it to make sure it can talk to the server.
func NewExampleClient() (*redis.Client, error) {
//redisHost := viper.Get(redisKey)
redisHost := "redis"
client := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:6379", redisHost),
Password: "",
DB: 0,
})
_, err := client.Ping().Result()
return client, err
}
func main() {
//env == DEMO_REDIS
//viper.SetEnvPrefix("demo")
//viper.BindEnv(redisKey)
client, err := NewExampleClient()
if err != nil {
panic(err)
}
defer client.Close()
value := time.Now().Format(time.RFC3339)
err = client.Set("KEY1", value, 0).Err()
if err != nil {
panic(err)
}
result := client.Get("KEY1")
if err = result.Err(); err != nil {
panic(err)
}
log.Printf("set KEY1 result %s", result.Val())
//fmt.Println(result.Val())
lockResult, err := client.SetNX("LOCK1", 1, (3 * time.Second)).Result()
if err != nil {
log.Fatalf("lock err %s", err)
}
log.Printf("lock result %v", lockResult)
unlockResult, err := client.Del("LOCK1").Result()
if err != nil {
log.Fatalf("unlock err %s", err)
}
log.Printf("unlock result %v", unlockResult)
time.Sleep(5 * time.Minute)
signals()
}
func signals() {
// Go signal notification works by sending `os.Signal`
// values on a channel. We'll create a channel to
// receive these notifications (we'll also make one to
// notify us when the program can exit).
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for
// signals. When it gets one it'll print it out
// and then notify the program that it can finish.
go func() {
sig := <-sigs
log.Println("sig ", sig)
done <- true
}()
// The program will wait here until it gets the
// expected signal (as indicated by the goroutine
// above sending a value on `done`) and then exit.
log.Println("awaiting signal")
<-done
log.Println("exiting")
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化