在k8s中部署一个可外部访问的Redis Sentinel

1.前提条件:

1.部署了multus
想要k8s外部能访问k8s内部的redis,redis-server启动时必须使用multus的IP
2.helm客户端安装

2.开始安装

准备3个multus ip

10.10.10.130
10.10.10.131
10.10.10.132

apiVersion: k8s.cni.cncf.io/v1
kind: NetworkAttachmentDefinition
metadata:name: net10-130-132namespace: default
spec:config: |-{"cniVersion": "0.3.1","name": "net10-130-132","type": "macvlan","master": "ens224","mode": "bridge","ipam": {"type": "whereabouts","range": "10.10.10.0/24", "range_start": "10.10.10.130","range_end": "10.10.10.132","routes": [{ "dst": "10.206.0.0/16", "gw": "10.10.10.1" }]}}

通过helm部署redis

helm pull bitnami/redis --version=16.13.2
helm install redis -f values.yaml . 

修改values.yaml

global:imageRegistry: ""imagePullSecrets: []storageClass: "vsan-csi" ##设置storage classredis:password: "password"  ##设置redis密码
kubeVersion: ""
nameOverride: ""
fullnameOverride: ""
commonLabels: {}
commonAnnotations: {}
secretAnnotations: {}
clusterDomain: cluster.local
extraDeploy: []
diagnosticMode:enabled: falsecommand:- sleepargs:- infinity
image:registry: docker.iorepository: bitnami/redistag: 6.2.7-debian-11-r11pullPolicy: IfNotPresentpullSecrets: []debug: falsearchitecture: replication
auth:enabled: true #开启redis密码sentinel: false ##关闭sentinel密码password: "password"existingSecret: ""existingSecretPasswordKey: ""usePasswordFiles: falsecommonConfiguration: |-# Enable AOF https://redis.io/topics/persistence#append-only-fileappendonly yes# Disable RDB persistence, AOF persistence already enabled.save ""
existingConfigmap: ""master:count: 1configuration: ""disableCommands:- FLUSHDB- FLUSHALLcommand: []args: []preExecCmds: []extraFlags: []extraEnvVars: []extraEnvVarsCM: ""extraEnvVarsSecret: ""containerPorts:redis: 6379startupProbe:enabled: falseinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 5successThreshold: 1failureThreshold: 5livenessProbe:enabled: trueinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 5successThreshold: 1failureThreshold: 5readinessProbe:enabled: trueinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 1successThreshold: 1failureThreshold: 5customStartupProbe: {}customLivenessProbe: {}customReadinessProbe: {}resources: ##设置master资源大小limits:cpu: 1000mmemory: 4096MiBrequests: cpu: 1000mmemory: 4096MiBpodSecurityContext:enabled: truefsGroup: 1001containerSecurityContext:enabled: truerunAsUser: 1001kind: StatefulSetschedulerName: ""updateStrategy:type: RollingUpdaterollingUpdate: {}priorityClassName: ""hostAliases: []podLabels: {}podAnnotations: {}shareProcessNamespace: falsepodAffinityPreset: ""podAntiAffinityPreset: softnodeAffinityPreset:type: ""key: ""values: []affinity: {}nodeSelector: {}tolerations: []topologySpreadConstraints: []dnsPolicy: ""dnsConfig: {}lifecycleHooks: {}extraVolumes: []extraVolumeMounts: []sidecars: []initContainers: []persistence:enabled: truemedium: ""sizeLimit: ""path: /datasubPath: ""storageClass: "vsan-csi"accessModes:- ReadWriteOncesize: 10Giannotations: {}selector: {}dataSource: {}existingClaim: ""service:type: ClusterIPports:redis: 6379nodePorts:redis: ""externalTrafficPolicy: ClusterextraPorts: []internalTrafficPolicy: ClusterclusterIP: ""loadBalancerIP: ""loadBalancerSourceRanges: []annotations: {}sessionAffinity: NonesessionAffinityConfig: {}terminationGracePeriodSeconds: 30replica:replicaCount: 3configuration: ""disableCommands:- FLUSHDB- FLUSHALLcommand: []args: []preExecCmds: []extraFlags: []extraEnvVars: []extraEnvVarsCM: ""extraEnvVarsSecret: ""externalMaster:enabled: falsehost: ""port: 6379containerPorts:redis: 6379startupProbe:enabled: trueinitialDelaySeconds: 10periodSeconds: 10timeoutSeconds: 5successThreshold: 1failureThreshold: 22livenessProbe:enabled: trueinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 5successThreshold: 1failureThreshold: 5readinessProbe:enabled: trueinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 1successThreshold: 1failureThreshold: 5customStartupProbe: {}customLivenessProbe: {}customReadinessProbe: {}resources:limits: cpu: 250mmemory: 256Mirequests: cpu: 250mmemory: 256MipodSecurityContext:enabled: truefsGroup: 1001containerSecurityContext:enabled: truerunAsUser: 1001schedulerName: ""updateStrategy:type: RollingUpdaterollingUpdate: {}priorityClassName: ""podManagementPolicy: ""hostAliases: []podLabels: {}podAnnotations: {}shareProcessNamespace: falsepodAffinityPreset: ""podAntiAffinityPreset: softnodeAffinityPreset:type: ""key: ""values: []affinity: {}nodeSelector: {}tolerations: []topologySpreadConstraints: []dnsPolicy: ""dnsConfig: {}lifecycleHooks: {}extraVolumes: []extraVolumeMounts: []sidecars: []initContainers: []persistence:enabled: truemedium: ""sizeLimit: ""path: /datasubPath: ""storageClass: "vsan-csi"accessModes:- ReadWriteOncesize: 10Giannotations: {}selector: {}dataSource: {}existingClaim: ""service:type: ClusterIPports:redis: 6379nodePorts:redis: ""externalTrafficPolicy: ClusterinternalTrafficPolicy: ClusterextraPorts: []clusterIP: ""loadBalancerIP: ""loadBalancerSourceRanges: []annotations: {}sessionAffinity: NonesessionAffinityConfig: {}terminationGracePeriodSeconds: 30autoscaling:enabled: falseminReplicas: 1maxReplicas: 11targetCPU: ""targetMemory: ""sentinel:enabled: trueimage:registry: docker.iorepository: bitnami/redis-sentineltag: 6.2.7-debian-11-r12pullPolicy: IfNotPresentpullSecrets: []debug: falsemasterSet: mymasterquorum: 2getMasterTimeout: 220automateClusterRecovery: falsedownAfterMilliseconds: 60000failoverTimeout: 18000parallelSyncs: 1configuration: ""command: []args: []preExecCmds: []extraEnvVars: []extraEnvVarsCM: ""extraEnvVarsSecret: ""externalMaster:enabled: falsehost: ""port: 6379containerPorts:sentinel: 26379startupProbe:enabled: trueinitialDelaySeconds: 10periodSeconds: 10timeoutSeconds: 5successThreshold: 1failureThreshold: 22livenessProbe:enabled: trueinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 5successThreshold: 1failureThreshold: 5readinessProbe:enabled: trueinitialDelaySeconds: 20periodSeconds: 5timeoutSeconds: 1successThreshold: 1failureThreshold: 5customStartupProbe: {}customLivenessProbe: {}customReadinessProbe: {}persistence:enabled: falsestorageClass: ""accessModes:- ReadWriteOncesize: 100Miannotations: {}selector: {}dataSource: {}medium: ""resources:limits: cpu: 250mmemory: 256Mirequests: cpu: 250mmemory: 256MicontainerSecurityContext:enabled: truerunAsUser: 1001lifecycleHooks: {}extraVolumes: []extraVolumeMounts: []service:type: ClusterIPports:redis: 6379sentinel: 26379nodePorts:redis: ""sentinel: ""externalTrafficPolicy: ClusterextraPorts: []clusterIP: ""loadBalancerIP: ""loadBalancerSourceRanges: []annotations: {}sessionAffinity: NonesessionAffinityConfig: {}terminationGracePeriodSeconds: 30networkPolicy:enabled: falseallowExternal: trueextraIngress: []extraEgress: []ingressNSMatchLabels: {}ingressNSPodMatchLabels: {}
podSecurityPolicy:create: falseenabled: false
rbac:create: falserules: []
serviceAccount:create: truename: ""automountServiceAccountToken: trueannotations: {}
pdb:create: falseminAvailable: 1maxUnavailable: ""
tls:enabled: falseauthClients: trueautoGenerated: falseexistingSecret: ""certificatesSecret: ""certFilename: ""certKeyFilename: ""certCAFilename: ""dhParamsFilename: ""metrics:enabled: trueimage:registry: docker.iorepository: bitnami/redis-exportertag: 1.43.0-debian-11-r4pullPolicy: IfNotPresentpullSecrets: []command: []redisTargetHost: "localhost"extraArgs: {}extraEnvVars: []containerSecurityContext:enabled: truerunAsUser: 1001extraVolumes: []extraVolumeMounts: []resources:limits: cpu: 250mmemory: 256Mirequests: cpu: 250mmemory: 256MipodLabels: {}podAnnotations:prometheus.io/scrape: "true"prometheus.io/port: "9121"service:type: ClusterIPport: 9121externalTrafficPolicy: ClusterextraPorts: []loadBalancerIP: ""loadBalancerSourceRanges: []annotations: {}serviceMonitor:enabled: truenamespace: ""interval: 30sscrapeTimeout: ""relabellings: []metricRelabelings: []honorLabels: falseadditionalLabels: {}prometheusRule:enabled: truenamespace: ""additionalLabels: {}rules:- alert: RedisDownexpr: redis_up{service="{{ template "common.names.fullname" . }}-metrics"} == 0for: 2mlabels:severity: errorannotations:summary: Redis® instance {{ "{{ $labels.instance }}" }} downdescription: Redis® instance {{ "{{ $labels.instance }}" }} is down- alert: RedisMemoryHighexpr: >redis_memory_used_bytes{service="{{ template "common.names.fullname" . }}-metrics"} * 100/redis_memory_max_bytes{service="{{ template "common.names.fullname" . }}-metrics"}> 90for: 2mlabels:severity: errorannotations:summary: Redis® instance {{ "{{ $labels.instance }}" }} is using too much memorydescription: |Redis® instance {{ "{{ $labels.instance }}" }} is using {{ "{{ $value }}" }}% of its available memory.- alert: RedisKeyEvictionexpr: |increase(redis_evicted_keys_total{service="{{ template "common.names.fullname" . }}-metrics"}[5m]) > 0for: 1slabels:severity: errorannotations:summary: Redis® instance {{ "{{ $labels.instance }}" }} has evicted keysdescription: |Redis® instance {{ "{{ $labels.instance }}" }} has evicted {{ "{{ $value }}" }} keys in the last 5 minutes.
volumePermissions:enabled: falseimage:registry: docker.iorepository: bitnami/bitnami-shelltag: 11-debian-11-r11pullPolicy: IfNotPresentpullSecrets: []resources:limits: {}requests: {}containerSecurityContext:runAsUser: 0sysctl:enabled: falseimage:registry: docker.iorepository: bitnami/bitnami-shelltag: 11-debian-11-r11pullPolicy: IfNotPresentpullSecrets: []command: []mountHostSys: falseresources:limits: {}requests: {}useExternalDNS:enabled: falsesuffix: ""annotationKey: external-dns.alpha.kubernetes.io/additionalAnnotations: {}

修改configMap redis-scripts

get_full_hostname() {hostname="$1"echo "${hostname}.${HEADLESS_SERVICE}"
}

替换为

get_full_hostname() {hostname="$1"if [[ "${hostname}" =~ 0$ ]]; thenecho "10.10.10.130"fiif [[ "${hostname}" =~ 1$ ]]; thenecho "10.10.10.131"fiif [[ "${hostname}" =~ 2$ ]]; thenecho "10.10.10.132"fi
}

然后将statefulset的replica从3改为0,

spec:template:metadata:annotations:k8s.v1.cni.cncf.io/networks: default/net10-130-132

再从0改为3。

3.测试连接:

测试工具 Another Redis Desktop Manager
在这里插入图片描述
在这里插入图片描述
连接OK

4.Springboot 连接redis

新建一个springboot项目
关键信息如下

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.xxxx</groupId><artifactId>redis-test</artifactId><version>0.0.1-SNAPSHOT</version><name>redis-test</name><description>redis-test</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.6.13</spring-boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--redis连接池--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot.version}</version>
<!--                <configuration>-->
<!--                    <mainClass>com.aecqauto.redistest.RedisTestApplication</mainClass>-->
<!--                    <skip>true</skip>-->
<!--                </configuration>--><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
</project>

application.yml

server:port: 8080spring:redis:#password: passwordlettuce:pool:# 连接池最大连接数(使用负值表示没有限制) 默认为8max-active: 8# 连接池中的最大空闲连接 默认为8max-idle: 8# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认为-1max-wait: -1ms# 连接池中的最小空闲连接 默认为 0min-idle: 0sentinel:# 主节点的别名master: mymasterpassword: password# sentinel服务的ip和端口nodes:- 10.10.10.130:26379- 10.10.10.131:26379- 10.10.10.132:26379

RedisController.java

package com.aecqauto.redistest.demos.web;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/redis")
public class RedisController {// 使用SpringBoot封装的RestTemplate对象@AutowiredRedisTemplate<String, String> redisTemplate;@RequestMapping("/get")public String get(String key) {String value = redisTemplate.opsForValue().get(key);return value;}@RequestMapping("/set")public String set(String key, String value) {redisTemplate.opsForValue().set(key, value);return "success";}
}

启动springboot项目并测试

设置key
在这里插入图片描述
获取key
在这里插入图片描述
测试成功

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

目标跟踪算法发展简史

单目标跟踪&#xff08;Single Object Tracking&#xff0c;SOT&#xff09;是计算机视觉领域中的一个重要研究方向&#xff0c;旨在在视频序列中持续定位并跟踪一个特定目标。随着计算机视觉和机器学习技术的飞速发展&#xff0c;单目标跟踪算法经历了从经典方法到深度学习的演…

使用LPT wiggler jtag自制三星单片机(sam88 core)编程器-S3F9454

写在前面 新年好&#xff0c;各位&#xff0c;今天来分享制作一个三星单片机的编程器 嘿嘿&#xff0c;x鱼垃圾佬元件库有些三星单片机s3f9454&#xff0c;编程器不想买&#xff0c;基本拿来拆件玩的。但&#xff0c;前些时候csdn下载到它的编程时序&#xff0c;自己来做个编程…

Spring 中的事件驱动模型

事件驱动的基本了解 事件模式也就是观察者模式&#xff0c;当一个对象改变的时候&#xff0c;所有依赖的对象都会收到一个通知。 Subject&#xff1a;抽象主题 Observer&#xff1a;具体主题 Concrete Subject&#xff1a;抽象观察者&#xff0c;在得到更新通知之后去更新自…

玉米植物结构受乙烯生物合成基因 ZmACS7 的调控

摘要&#xff1a; 植物高度和叶片角度是玉米&#xff08;Zea mays&#xff09;植物结构的两个关键决定因素&#xff0c;与高种植密度下的抗倒伏性和冠层光合作用密切相关。这两个性状主要由几种植物激素调节。然而&#xff0c;乙烯在调节玉米植物结构中的机制&#xff0c;特别…

Java高频面试之SE-15

hello啊&#xff0c;各位观众姥爷们&#xff01;&#xff01;&#xff01;本牛马baby今天又来了&#xff01;哈哈哈哈哈嗝&#x1f436; String 怎么转成 Integer 的&#xff1f;它的原理是&#xff1f; 在 Java 中&#xff0c;要将 String 转换为 Integer 类型&#xff0c;可…

解锁Java中的国密算法:安全保障的密钥

一、引言 在数字化浪潮席卷全球的当下&#xff0c;信息安全已然成为国家、企业乃至个人无法忽视的重要议题。国密算法&#xff0c;作为我国自主研发的密码算法体系&#xff0c;宛如坚固的盾牌&#xff0c;为国家信息安全筑起了一道坚不可摧的防线。它的诞生&#xff0c;不仅承载…

金融场景 PB 级大规模日志平台:中信银行信用卡中心从 Elasticsearch 到 Apache Doris 的先进实践

导读&#xff1a;中信银行信用卡中心每日新增日志数据 140 亿条&#xff08;80TB&#xff09;&#xff0c;全量归档日志量超 40PB&#xff0c;早期基于 Elasticsearch 构建的日志云平台&#xff0c;面临存储成本高、实时写入性能差、文本检索慢以及日志分析能力不足等问题。因此…

1.2.神经网络基础

目录 1.2.神经网络基础 1.2.1.Logistic回归 1.2.2 梯度下降算法 1.2.3 导数 1.2.4 向量化编程 1.2.5 正向传播与反向传播 1.2.6.练习 1.2.神经网络基础 1.2.1.Logistic回归 1.2.1.1.Logistic回归 逻辑回归是一个主要用于二分分类类的算法。那么逻辑回归是给定一个x ,…

MIAOYUN信创云原生项目亮相西部“中试”生态对接活动

近日&#xff0c;以“构建‘中试’生态&#xff0c;赋能科技成果转化”为主题的“科创天府智汇蓉城”西部“中试”生态对接活动在成都高新区菁蓉汇隆重开幕。活动分为成果展览、“中试”生态主场以及成果路演洽谈对接三大板块。在成果展览环节&#xff0c;成都元来云志科技有限…

【vitePress】基于github快速添加评论功能(giscus)

一.添加评论插件 使用giscus来做vitepress 的评论模块&#xff0c;使用也非常的简单&#xff0c;具体可以参考&#xff1a;giscus 文档&#xff0c;首先安装giscus npm i giscus/vue 二.giscus操作 打开giscus 文档&#xff0c;如下图所示&#xff0c;填入你的 github 用户…

成就与远见:2024年技术与思维的升华

个人主页&#xff1a;chian-ocean 前言: 2025年1月17日&#xff0c;2024年博客之星年度评选——创作影响力评审的入围名单公布。我很荣幸能够跻身Top 300&#xff0c;虽然与顶尖博主仍有一定差距&#xff0c;但这也为我提供了更加明确的发展方向与指引。展望崭新的2025年&…

一文了解如何在Qt中间集成Halcon窗口并在子线程显示(附工程源码下载链接)

在基于图像处理的开发中&#xff0c;Halcon作为功能强大的图像处理库&#xff0c;经常需要与Qt结合&#xff0c;以便通过Qt提供的UI功能更好地显示和交互。本文将讲解如何在Qt中集成Halcon窗口&#xff0c;并通过子线程实现Halcon图像的显示&#xff0c;保证主线程的流畅运行。…

游戏引擎学习第80天

Blackboard&#xff1a;增强碰撞循环&#xff0c;循环遍历两种类型的 t 值 计划对现有的碰撞检测循环进行修改&#xff0c;以便实现一些新的功能。具体来说&#xff0c;是希望处理在游戏中定义可行走区域和地面的一些实体。尽管这是一个2D游戏&#xff0c;目标是构建一些更丰富…

深度学习-89-大语言模型LLM之AI应用开发的基本概念

文章目录 1 什么是智能体(Agent)2 什么是大语言模型(LLM)2.1 LLM的训练及使用2.2 Transformer架构2.3 基于LLM的Agent框架3 什么是检索增强生成(RAG)3.1 RAG是什么3.2 生成式AI应用开发3.3 RAG的整体流程3.4 RAG技术3.4.1 简单RAG(Simple RAG)3.4.2 校正RAG(Corrective RAG)3.4…

电子科大2024秋《大数据分析与智能计算》真题回忆

考试日期&#xff1a;2025-01-08 课程&#xff1a;成电信软学院-大数据分析与智能计算 形式&#xff1a;开卷 考试回忆版 简答题&#xff08;4*15&#xff09; 1. 简述大数据的四个特征。分析每个特征所带来的问题和可能的解决方案 2. HDFS的架构的主要组件有哪些&#xff0…

Windows电脑安装USB Redirector并实现内外网跨网USB共享通信访问

文章目录 前言1. 安装下载软件1.1 内网安装使用USB Redirector1.2 下载安装cpolar内网穿透 2. 完成USB Redirector服务端和客户端映射连接3. 设置固定的公网地址 前言 我们每天都在与各种智能设备打交道&#xff0c;从手机到电脑&#xff0c;再到各种外设&#xff0c;它们已经…

Docker 实现MySQL 主从复制

一、拉取镜像 docker pull mysql:5.7相关命令&#xff1a; 查看镜像&#xff1a;docker images 二、启动镜像 启动mysql01、02容器&#xff1a; docker run -d -p 3310:3306 -v /root/mysql/node-1/config:/etc/mysql/ -v /root/mysql/node-1/data:/var/lib/mysql -e MYS…

多监控m3u8视频流,怎么获取每个监控的封面图(纯前端)

文章目录 1.背景2.问题分析3.解决方案3.1解决思路3.2解决过程3.2.1 封装播放组件3.2.2 隐形的视频div3.2.3 截取封面图 3.3 结束 1.背景 有这样一个需求&#xff1a; 给你一个监控列表&#xff0c;每页展示多个监控&#xff08;至少12个&#xff0c;m3u8格式&#xff09;&…

VS Code AI开发之Copilot配置和使用详解

随着AI开发工具的迅速发展&#xff0c;GitHub Copilot在Cursor、Winsuf、V0等一众工具的冲击下&#xff0c;推出了免费版本。接下来&#xff0c;我将为大家介绍GitHub Copilot的配置和使用方法。GitHub Copilot基于OpenAI Codex模型&#xff0c;旨在为软件开发者提供智能化的代…

前端开发Web

Ajax 概念:Asynchronous JavaScriptAnd XML&#xff0c;异步的JavaScript和XML 作用: 数据交换:通过Ajax可以给服务器发送请求&#xff0c;并获取服务器响应的数据。 异步交互:可以在不重新加载整个页面的情况下&#xff0c;与服务器交换数据并更新部分网页的…