go mod init
go get github.com/go-redis/redis
package main
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
"time"
)
// 定时任务Task 执行代码
func init() {
lockKey := "task:test:mytest"
client := GetRedisClient()
defer client.Close()
lockRes := client.SetNX(lockKey, time.Now().Unix(), time.Minute*1).Val()
if !lockRes {
return
}
defer client.Del(lockKey)
// 下面执行任务代码
// service := services.func{}
}
// 连接redis服务器 并返回客户端连接对像
func GetRedisClient() *redis.Client{
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "", // no password set
DB: 0, // use default DB
})
_, err := client.Ping().Result()
if err != nil {
panic(err)
}
return client
}
type Person struct {
Name string
Age int
}
func main(){
client :=GetRedisClient() // 获取客户端连接对像
defer client.Close()
// 设置值
err:= client.Set("myName","Lyh",0).Err()
if err!=nil{
fmt.Println("redis存值出错",err)
}
// 获取值
myName,err:=client.Get("myName").Result()
if err!=nil{
fmt.Println("redis取值出错",err)
}
fmt.Println("值:",myName)
// 删除Key
client.Del("myName")
// 操作Hash
var p Person
p.Name="中国张三"
p.Age=10
strP,err:= json.Marshal(p)
// HSet 设置Hash的值
err = client.HSet("personAll","chinses",strP).Err()
if err!=nil{
fmt.Println("中国张三有问题",err)
}
// HGet 获取Hash的值
v:= client.HGet("personAll","chinses").Val()
fmt.Println("redis的Hash值:",v)
// 删除hash
client.HDel("personAll","chinses")
}