一、redis连接
引入包"github.com/go-redis/redis/v8"
var(
redisInstance *redis.Client
)
func init() {
redisI :=redis.NewClient(&redis.Options{
Addr:“http://192.168.90.86:6379”,
Password:"123456", // 设置密码
DB:0, // use default DB
})
redisInstance = redisI
}
func GetRedis() *redis.Client{
return redisInstance
}
二、redis,string类型存取
var ctx = context.TODO()
/**
* 判断key是否存在
*/
func RedisExists(keystring) (bool,error) {
client :=conn.GetRedis()
if client !=nil{
r,err := client.Exists(ctx,key).Result()
if err ==nil {
if r ==1 {
return true, nil
}else{
return false, nil
}
}
}
return false, errors.New("查询key失败")
}
/**
* redis设置值
*/
func SetRedisCache(keystring,valueinterface{},durationtime.Duration)error {
client :=conn.GetRedis()
if client !=nil{
_,err := client.Set(ctx,key,value,duration).Result()
return err
}else{
return errors.New("redis连接失败")
}
}
/**
* redis获取值
*/
func GetRedisCache(keystring) (interface{},error) {
client :=conn.GetRedis()
if client !=nil{
r,err := client.Get(ctx,key).Result()
if err ==redis.Nil {
return nil,nil
}else if err !=nil {
return nil,err
}else {
return r,nil
}
}else{
return nil,errors.New("redis连接失败")
}
}
/**
* 移除
*/
func ClearRedisCache(keystring) {
client :=conn.GetRedis()
if client !=nil{
client.Move(ctx,key,0)
}
}
三、docker启动redis
拉取镜像
docker pull redis:latest
//docker启动redis镜像
docker run --name my_redis -p 6379:6379 -d --restart=always redis:latest redis-server --appendonly yes --requirepass "123456"
//测试
redis-cli -h 192.168.90.86 -p 6379
10.249.91.86:6379> set text1 2
(error) NOAUTH Authentication required.
192.168.90.86:6379> auth 123456
OK
192.168.90.86:6379> set text1 2
OK
192.168.90.86:6379> keys *
1) "text1"
2) "text"
10.249.91.86:6379>
网友评论