Redis-cli Go代码

news2024/9/21 16:43:02

Redis-cli Go代码

安装

go get github.com/redis/go-redis/v9

建立连接

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
)

client := redis.NewClient(&redis.Options{
	Addr:	  "localhost:6379",
	Password: "", // no password set
	DB:		  0,  // use default DB
})

Options 配置

// Options keeps the settings to set up redis connection.
type Options struct {
	// The network type, either tcp or unix.
	// Default is tcp.
	Network string
	// host:port address.
	Addr string

	// ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
	ClientName string

	// Dialer creates new network connection and has priority over
	// Network and Addr options.
	Dialer func(ctx context.Context, network, addr string) (net.Conn, error)

	// Hook that is called when new connection is established.
	OnConnect func(ctx context.Context, cn *Conn) error

	// Use the specified Username to authenticate the current connection
	// with one of the connections defined in the ACL list when connecting
	// to a Redis 6.0 instance, or greater, that is using the Redis ACL system.
	Username string
	// Optional password. Must match the password specified in the
	// requirepass server configuration option (if connecting to a Redis 5.0 instance, or lower),
	// or the User Password when connecting to a Redis 6.0 instance, or greater,
	// that is using the Redis ACL system.
	Password string
	// CredentialsProvider allows the username and password to be updated
	// before reconnecting. It should return the current username and password.
	CredentialsProvider func() (username string, password string)

	// Database to be selected after connecting to the server.
	DB int

	// Maximum number of retries before giving up.
	// Default is 3 retries; -1 (not 0) disables retries.
	MaxRetries int
	// Minimum backoff between each retry.
	// Default is 8 milliseconds; -1 disables backoff.
	MinRetryBackoff time.Duration
	// Maximum backoff between each retry.
	// Default is 512 milliseconds; -1 disables backoff.
	MaxRetryBackoff time.Duration

	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout time.Duration
	// Timeout for socket reads. If reached, commands will fail
	// with a timeout instead of blocking. Supported values:
	//   - `0` - default timeout (3 seconds).
	//   - `-1` - no timeout (block indefinitely).
	//   - `-2` - disables SetReadDeadline calls completely.
	ReadTimeout time.Duration
	// Timeout for socket writes. If reached, commands will fail
	// with a timeout instead of blocking.  Supported values:
	//   - `0` - default timeout (3 seconds).
	//   - `-1` - no timeout (block indefinitely).
	//   - `-2` - disables SetWriteDeadline calls completely.
	WriteTimeout time.Duration
	// ContextTimeoutEnabled controls whether the client respects context timeouts and deadlines.
	// See https://redis.uptrace.dev/guide/go-redis-debugging.html#timeouts
	ContextTimeoutEnabled bool

	// Type of connection pool.
	// true for FIFO pool, false for LIFO pool.
	// Note that FIFO has slightly higher overhead compared to LIFO,
	// but it helps closing idle connections faster reducing the pool size.
	PoolFIFO bool
	// Maximum number of socket connections.
	// Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS.
	PoolSize int
	// Amount of time client waits for connection if all connections
	// are busy before returning an error.
	// Default is ReadTimeout + 1 second.
	PoolTimeout time.Duration
	// Minimum number of idle connections which is useful when establishing
	// new connection is slow.
	MinIdleConns int
	// Maximum number of idle connections.
	MaxIdleConns int
	// ConnMaxIdleTime is the maximum amount of time a connection may be idle.
	// Should be less than server's timeout.
	//
	// Expired connections may be closed lazily before reuse.
	// If d <= 0, connections are not closed due to a connection's idle time.
	//
	// Default is 30 minutes. -1 disables idle timeout check.
	ConnMaxIdleTime time.Duration
	// ConnMaxLifetime is the maximum amount of time a connection may be reused.
	//
	// Expired connections may be closed lazily before reuse.
	// If <= 0, connections are not closed due to a connection's age.
	//
	// Default is to not close idle connections.
	ConnMaxLifetime time.Duration

	// TLS Config to use. When set, TLS will be negotiated.
	TLSConfig *tls.Config

	// Limiter interface used to implement circuit breaker or rate limiter.
	Limiter Limiter

	// Enables read only queries on slave/follower nodes.
	readOnly bool
}

初始化连接

var Client *redis.Client
// 建立新连接时的回调
func OnConnect(ctx context.Context, cn *redis.Conn) error {
	if cn != nil {
		fmt.Println("connect ok")
	}
	return nil
}
//初始化redis
func InitRedis() {
	if Client == nil {
		fmt.Println("init client")
		Client = redis.NewClient(&redis.Options{
			Addr:      "localhost:6379",
			Password:  "", // no password set
			DB:        0,  // use default DB
			OnConnect: OnConnect,
		})
	}
}

// Set 
func Set(ctx context.Context, key string, val interface{}, duration time.Duration) error {
	return Client.Set(ctx, key, val, duration).Err()
}
// Get
func Get(ctx context.Context, key string) string {
	val, err := Client.Get(ctx, key).Result()
	if err != nil {
		panic(err)
	}
	return val
}

string 测试Get Set 方法

func TestRedis(t *testing.T) {
	InitRedis()
	ctx := context.Background()
	err := Set(ctx, "zdm", "赵德满", 1*time.Hour)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(Get(ctx, "zdm"))
}

在这里插入图片描述

存储hash

func TestHash(t *testing.T) {
	InitRedis()
	session := map[string]string{"name":"zdm","company":"sm","age":"24"}
	ctx := context.Background()
	for k,v := range session {
		err := HSet(ctx,"user:session",k,v)
		if err != nil {
			fmt.Println(err.Error())
		}
	}
	res,err := HGetAll(ctx,"user:session")
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(res)
}

在这里插入图片描述

连接到Redis群集

var ReCluster *redis.ClusterClient
func InitRedisCluster() {
	if ReCluster == nil {
		ReCluster = redis.NewClusterClient(&redis.ClusterOptions{
			Addrs: []string{":16379", ":16380", ":16381", ":16382", ":16383", ":16384"},

			// To route commands by latency or randomly, enable one of the following.
			//RouteByLatency: true,
			//RouteRandomly: true,
		})
	}
}

使用Redis 集群扩展

Redis使用称为Redis Cluster的部署拓扑进行水平扩展。本主题将教您如何在生产中设置、测试和操作Redis集群。您将从最终用户的角度了解Redis Cluster的可用性和一致性特征。

如果您计划运行生产Redis Cluster部署,或者想更好地了解Redis Cluster如何在内部工作,请参阅Redis Cluster规范(https://redis.io/docs/reference/cluster-spec/)。要了解Redis Enterprise如何处理缩放,请参阅Redis Enterprise的线性缩放(https://redis.com/redis-enterprise/technology/linear-scaling-redis-enterprise)。

创建和使用一个Redis 集群

包含以下几个步骤

  • Create a Redis Cluster (创建一个Redis 集群)
  • Interact with the cluster (与集群交互)
  • Write an example app with redis-rb-cluster (编写一个带有redis-rb集群的示例应用程序)
  • Reshard the cluster
  • A more interesting example application
  • Test the failover (测试故障切换)
  • Manual failover (手动故障转移)
  • Add a new node (添加一个新节点)
  • Remove a node (移除一个新节点)
  • Replica migration (复制副本迁移)
  • Upgrade nodes in a Redis Cluster (升级redis 中集群的节点)
  • 迁移到Redis群集 (迁移到redis 集群)

首先我们要熟悉创建集群的要求

Requirements to create a Redis Cluster (创建集群的要求)
To create a cluster, the first thing you need is to have a few empty Redis instances running in cluster mode.
At minimum, set the following directives in the redis.conf file:
要创建一个集群,首先需要有几个空的Redis实例在集群模式下运行。
至少在redis.conf文件中设置以下指令:

port 7000
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes

要启用群集模式,请将启用群集的指令设置为yes。每个实例还包含存储该节点配置的文件的路径,默认情况下为nodes.conf。人类永远不会接触该文件;它只是在启动时由Redis Cluster实例生成,并在每次需要时更新。
请注意,按预期工作的最小集群必须至少包含三个主节点。对于部署,我们强烈建议使用六节点集群,其中包含三个主节点和三个副本。
您可以通过创建以下目录来本地测试这一点,这些目录以您将在任何给定目录中运行的实例的端口号命名。

mkdir cluster-test
cd cluster-test
mkdir 7000 7001 7002 7003 7004 7005

在这里插入图片描述
每个文件夹下放的redis-conf 文件,port 改为对应的7001 7002…
daemonize no # 改为yes 支持后台进程启动

./redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001  127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005  --cluster-replicas 1

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/453489.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

支付宝 网站支付Demo 案例【沙箱环境】IDEA如何配置启动Eclipse项目

前言 在跑支付宝提供的支付案例Demo的时候&#xff0c;遇到了一些问题。支付宝提供的Demo是用Eclipse跑的JAVAEE项目。我想用IDEA来跑一下看看、结果使用习惯了Mavne管理jar包和SpringBoot项目。启动web项目的时候&#xff0c;还遇到一些问题。特此记录遇到的一些小问题。顺便回…

c++之常见函数

文章目录 一、inline函数二、函数重载三、函数模板 一、inline函数 1.当进行函数的调用时&#xff0c;系统要建立栈空间&#xff0c;保护现场&#xff0c;传递参数等等&#xff0c;这些工作都需要系统时间和空间得开销然而inline 函数是以空间换时间的做法&#xff0c;省去调用…

FL Studio 21最新发布的版本主要的新功能

FL Studio 21是最新发布的版本,其主要的新功能有: 1. 全新的UI设计:FL 21采用全新的 FLAT UI 设计风格,简洁而不简单,颜值大大提高。 2. 多窗口支持:可以将FL Studio窗口分别显示在不同的显示器上,实现屏幕间切换和多视图编辑。 3. 混音台增强:新增后置通道、多输入输入和多…

反垃圾邮件产品技术要求和测试评价方法

声明 本文是学习信息安全技术 反垃圾邮件产品技术要求和测试评价方法. 而整理的学习笔记,分享出来希望更多人受益,如果存在侵权请及时联系我们 反垃圾邮件产品等级划分 根据产品功能要求和安全保证要求的不同&#xff0c;以及反垃圾邮件产品适用应用环境的不同&#xff0c;将…

ROS1学习笔记:常用可视化工具的使用(ubuntu20.04)

参考B站古月居ROS入门21讲&#xff1a;常用可视化工具的实现 基于VMware Ubuntu 20.04 Noetic版本的环境 文章目录 一、日志输出工具&#xff1a;rqt_console二、绘制数据曲线&#xff1a;rqt_plot三、 图像渲染工具&#xff1a;rqt_image_view四、图形界面总接口&#xff1a;r…

FE之TSNE:基于MNIST手写数字数据集利用T-SNE/TSNE方法实现高维数据集可视化应(二维可视化和三维可视化)应用案例之详细攻略

FE之TSNE&#xff1a;基于MNIST手写数字数据集利用T-SNE/TSNE方法实现高维数据集可视化应(二维可视化和三维可视化)应用案例之详细攻略 目录 基于MNIST手写数字数据集利用T-SNE/TSNE方法实现高维数据集可视化应(二维可视化和三维可视化)应用案例 # 1、定义数据集 # 2、数据预…

docker部署springboot(jar)项目的方式概括

1、docker挂载目录 实现原理&#xff1a;docker中只需要安装一个JDK镜像&#xff0c;把该镜像的目录挂载到外部的Linux中&#xff0c;如挂载到/usr/data/jar&#xff0c;我们只需要把Jenkins构建的jar文件传输到该目录中&#xff0c;在通过docker命令启动jar即可&#xff1a; …

【代码随想录】刷题Day5

1.链表重复节点删除 82. 删除排序链表中的重复元素 II 前后指针实现 1.做这道题最大的感受就是&#xff1a;不要觉得开辟空间浪费&#xff0c;多用临时变量去记录。越精确越容易成功 2.首先没有节点或者一个节点直接返回 3.因为头部会出现一样元素的情况&#xff0c;以至于我不…

C语言之详解静态变量static

在C语言中static是用来修饰变量和函数的&#xff0c;这篇文章详细介绍了static主要作用&#xff0c;文章中有详细的代码实例&#xff0c;需要的朋友可以参考阅读 在C语言中&#xff1a; static是用来修饰变量和函数的 static主要作用为: 1. 修饰局部变量 - 静态局部变量 2. …

linux软件安装指令---yum和rpm

这里写目录标题 一 yum指令1. yum install 软件名2. yum remove 软件名3 检查已经安装成功的软件 二 rpm指令1 rpm -q2 rpm -qa|less3 rpm -qa| grep python4 搜索文件的详细信息5 查询一个rpm中的包安装到哪里去了6 查询一个文件属于那个包7 软件包的卸载 三 总结四 示范安装 …

【面试系列】四种经典限流算法讲解

固定窗口限流算法 介绍 固定窗口限流算法&#xff08;Fixed Window Rate Limiting Algorithm&#xff09;是一种最简单的限流算法&#xff0c;其原理是在固定时间窗口(单位时间)内限制请求的数量。该算法将时间分成固定的窗口&#xff0c;并在每个窗口内限制请求的数量。具体来…

锦江展焕新演绎,憬黎公寓住造理想

2023年4月19-21日&#xff0c;“万物春生&#xff0c;赴锦程”锦江酒店&#xff08;中国区&#xff09;投资加盟品鉴会&#xff0c;在上海世博展览馆完美收官。这是一场迎着酒店行业复苏浪潮的年度盛会。 插图丨锦江酒店&#xff08;中国区&#xff09; 作为锦江酒店&#xff…

60 openEuler 22.03-LTS 搭建MySQL数据库服务器-安装、运行和卸载

文章目录 60 openEuler 22.03-LTS 搭建MySQL数据库服务器-安装、运行和卸载60.1 安装60.2 运行60.3 卸载 60 openEuler 22.03-LTS 搭建MySQL数据库服务器-安装、运行和卸载 60.1 安装 配置本地yum源&#xff0c;详细信息请参考《openEuler 22.03-LTS 搭建repo服务器》。 清除…

JavaWeb01(WEB环境的搭建)

目录 一.JDK 1.1 JDK是什么? 1.2 如何下载和安装jdk? 1.3 如何配置环境变量? 1.4 如何测试java环境变量是否配置成功? 二.Tomcat 2.1 Tomcat是什么? 2.2 为什么需要使用它? 2.3 如何下载? 2.4 了解Tomcat目录结构 2.5 如何修改Tomcat端口号(0-65535) 2.6 如何使…

Nginx的优化及防盗链

Nginx程序优化 模块 ngx_http_access_module模块 访问模块 ngx_http_auth_basic_module模块 用户访问控制 ngx_http_stub_status_module模块 查看http状态统计模块 ngx_http_gzip_module模块 压缩模块 ngx_http_ssl_module模块 设置http的连接模块 ngx_http_rewrite_mod…

Python selenium 模块使用find_element_by_id无效

一、发生异常: 二、原因 查询安装selenium的版本是4.5.0 这个版本不支持页面对象的定位find_element_by_id方法&#xff0c;以前版本支持这些进行元素定位&#xff1a; find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_elem…

找工作半年,四月成功拿到华为offer,分享一波面经...

前言 不论是校招还是社招都避免不了各种⾯试、笔试&#xff0c;如何去准备这些东⻄就显得格外重要。不论是笔试还是⾯试都是有章可循的&#xff0c;我这个“有章可循”说的意思只是说应对技术⾯试是可以提前准备&#xff0c;所谓不打无准备的仗就是这个道理。 以下为大家&…

【李宏毅】Bert家族

课程资料来自李宏毅老师油土鳖频道的BERT家族教程&#xff1a;上&#xff0c;下。 这两章主要是如何在pre-train的模型上做fine-turn&#xff0c;如何利用大模型来做自己的task。 目录 前言 什么是预训练 What is pre-train model 如何微调 How to fine-tune 入参 出参 …

[架构之路-174]-《软考-系统分析师》-5-数据库系统-7-数据仓库技术与数据挖掘技术

5 . 7 数据仓库技术 数据仓库是一个面向主题的、集成的、相对稳定的、反映历史变化的数据集合&#xff0c;用于支持管理决策。近年来&#xff0c;人们对数据仓库技术的关注程度越来越尚&#xff0c;其原因是过去的几十年中&#xff0c;建设了无数的应用系统&#xff0c;积累了…

5G 智慧教育解决方案(ppt可编辑)

本资料来源公开网络&#xff0c;仅供个人学习&#xff0c;请勿商用&#xff0c;如有侵权请联系删除 5G智慧教育-系统架构图 教学-远程互动教学系统架构图 平安校园-整体系统架构 平安校园&#xff1a;安全管理 平安校园-安全管理 视频监控 统一接入 统一管理 应急联动 系统通…