首页 » Redis, 开发语言 » Go语言(GO lang)连接Redis使用redigo

Go语言(GO lang)连接Redis使用redigo

之前有简单测试golang连接oracle和postgresql,最近刚好有客户问GOlang连接redis如何增加密码,因为安全要求,这里简单记录,安装redis省略参考<Redis学习01之安装Redis6 on Linux 7>, go安装参考《Go语言(GO lang)连接Oracle Database使用godror》。

目前常用的go连接redis的驱动有go-redis和redigo.  这篇使用redigo.

安装redigo
这里是在windows客户端,需要先安装git(cmd 输入git验证)

D:\code\gotest>go get -u github.com/garyburd/redigo/redis

启动redis 服务

[root@localhost redis]# export REDIS_HOME=/usr/soft/redis
[root@localhost redis]# export PATH=$PATH:$REDIS_HOME/bin
[root@localhost redis]#  redis-server
2140:C 24 Jun 2023 22:26:02.229 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
2140:C 24 Jun 2023 22:26:02.229 # Redis version=6.0.5, bits=64, commit=00000000, modified=0, pid=2140, just started
2140:C 24 Jun 2023 22:26:02.229 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
2140:M 24 Jun 2023 22:26:02.230 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 6.0.5 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 2140
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

2140:M 24 Jun 2023 22:26:02.230 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
2140:M 24 Jun 2023 22:26:02.230 # Server initialized
2140:M 24 Jun 2023 22:26:02.230 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
2140:M 24 Jun 2023 22:26:02.230 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
2140:M 24 Jun 2023 22:26:02.318 * Loading RDB produced by version 6.0.5
2140:M 24 Jun 2023 22:26:02.318 * RDB age 94822224 seconds
2140:M 24 Jun 2023 22:26:02.318 * RDB memory usage when created 0.77 Mb
2140:M 24 Jun 2023 22:26:02.319 * DB loaded from disk: 0.088 seconds
2140:M 24 Jun 2023 22:26:02.319 * Ready to accept connections

[root@localhost ~]# netstat  -an|grep 6379
tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:41762         127.0.0.1:6379          ESTABLISHED
tcp        0      0 127.0.0.1:6379          127.0.0.1:41762         ESTABLISHED
tcp6       0      0 :::6379                 :::*                    LISTEN
[root@localhost ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:cf:84:40 brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.110/24 brd 192.168.56.255 scope global enp0s3
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fecf:8440/64 scope link
       valid_lft forever preferred_lft forever

Note:
如果无netstat命令(yum install net-tools). 监听在虚机的6379 port.

无密码认证连接redis

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
)


func ConnRedis1() {
	conn, err := redis.Dial("tcp", "192.168.56.110:6379")
	if err != nil {
		fmt.Println("conn err :", err)
		return
	}
	fmt.Println("连接成功!")
	defer conn.Close()

}

func String() (int, error) {
	// 连接
	conn, err := redis.Dial("tcp", "192.168.56.110:6379")
	if err != nil {
		return 0, err
	}
	fmt.Println("连接成功!")
	defer conn.Close()
	// set值
	_, err = conn.Do("set", "id", 1001)
	if err != nil {
		return 0, err
	}
	fmt.Println("set成功!")
	// get值
	res, err := redis.Int(conn.Do("get", "id"))
	if err != nil {
		return 0, err
	}
	fmt.Println("get成功!")
	return res, nil
}


func main(){
   fmt.Println(String())
}

连接调试

D:\code\gotest>go run connectredis.go
连接成功!
0 DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password 
is requested to clients. In this mode connections are only accepted from the loopback interface. 
If you want to connect from external computers to Redis you may adopt one of the following solutions:
1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 
2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 
3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 
4) Setup a bind address or an authentication password. 
NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

禁用保护模式

127.0.0.1:6379> CONFIG SET protected-mode no
OK

D:\code\gotest>go run connectredis.go
连接成功!
set成功!
get成功!
1001 

服务端验证

127.0.0.1:6379> CONFIG SET protected-mode no
OK

127.0.0.1:6379> get id
"1001"
127.0.0.1:6379>

Redis配置密码
1,修改redis配置文件

//关闭本地监听或者改为0.0.0.0
# bind 127.0.0.1
//保护模式
protected-mode no
//去掉 # 号变requirepass foobared ,注:foobared是密码;
#requirepass foobared

2,命令行
命令行配置不用重启 config set requirepass 123456

仅为演示连接,我们使用方法2

# server

127.0.0.1:6379> CONFIG SET protected-mode no
OK
127.0.0.1:6379> get id
"1001"
127.0.0.1:6379> config set requirepass 123456
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "123456"
127.0.0.1:6379>

# client

[root@localhost ~]# redis-cli
127.0.0.1:6379> set id 1
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> set id 1
OK
127.0.0.1:6379> get id
"1"

redigo增加密码

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
)


func ConnRedis1() {
	conn, err := redis.Dial("tcp", "192.168.56.110:6379")
	if err != nil {
		fmt.Println("conn err :", err)
		return
	}
	fmt.Println("连接成功!")
	defer conn.Close()

}

func String() (int, error) {
	// 连接
	conn, err := redis.Dial("tcp", "192.168.56.110:6379")
		
	if err != nil {
		return 0, err
	}
	
	if _, err := conn.Do("AUTH", "123456"); err != nil {
				conn.Close()
				return 0, err
			}
			
	fmt.Println("连接成功!")
	defer conn.Close()
	// set值
	_, err = conn.Do("set", "id", 1001)
	if err != nil {
		return 0, err
	}
	fmt.Println("set成功!")
	// get值
	res, err := redis.Int(conn.Do("get", "id"))
	if err != nil {
		return 0, err
	}
	fmt.Println("get成功!")
	return res, nil
}


func main(){
   fmt.Println(String())
}

测试

# client
D:\code\gotest>go run connectredis.go
连接成功!
set成功!
get成功!
1001 


# server
127.0.0.1:6379> get id
"1"
127.0.0.1:6379> get id
"1001"
127.0.0.1:6379>


— enjoy —

打赏

,

对不起,这篇文章暂时关闭评论。