在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.mzph.cn/bicheng/68748.shtml

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

相关文章

使用tritonserver完成clip-vit-large-patch14图像特征提取模型的工程化。

1、关于clip-vit-large-patch14模型 关于openapi开源的clip-vit-large-patch14模型的特征提取&#xff0c;可以参考之前的文章&#xff1a;Elasticsearch向量检索需要的数据集以及768维向量生成这篇文章详细介绍了模型的下载地址、使用方式、测试脚本&#xff0c;可以让你一步…

偏序关系.

一、偏序&#xff08;半序&#xff09;关系 偏序关系 自反反对称传递性 二、全序&#xff08;线序、链&#xff09;关系 三、偏序集中的重要元素 1. 极大元与极小元 极大元找所在集合的一个或几个最高点&#xff1b; 极小元找所在集合的一个或几个最低点。 2. 最大元与最小…

2024嵌入式系统的未来发展与技术洞察分享

时间如白驹过隙&#xff0c;不知不觉又是一年&#xff0c;这一年收获满满。接下来&#xff0c;将本年度对技术的感悟和洞察分析如下&#xff0c;希望对大家有所帮助。 在过去几十年里&#xff0c;嵌入式系统技术迅速发展&#xff0c;成为现代电子设备和智能硬件的核心组成部分。…

AQS公平锁与非公平锁之源码解析

AQS加锁逻辑 ReentrantLock.lock public void lock() {sync.acquire(1);}AbstractQueuedSynchronizer#acquire public final void acquire(int arg) {if (!tryAcquire(arg) &&acquireQueued(addWaiter(Node.EXCLUSIVE), arg))selfInterrupt();}addWaiter就是将节点加入…

数字电子技术基础(十五)——MOS管的简单介绍

目录 1 MOS的简单介绍 1.1 MOS简介 1.2 MOS管的基本结构 1.3 MOS管工作时的三个区域 1.4 MOSEF的结构的工作原理 1 MOS的简单介绍 1.1 MOS简介 绝缘栅型场效应管&#xff0c;简称MOS管&#xff0c;全称为金属-氧化物-半导体场效应晶体管&#xff08;Metal-Oxide-Semic…

基础入门-传输加密数据格式编码算法密文存储代码混淆逆向保护安全影响

知识点&#xff1a; 1、传输格式&传输数据-类型&编码&算法 2、密码存储&代码混淆-不可逆&非对称性 一、演示案例-传输格式&传输数据-类型&编码&算法 传输格式 JSON XML WebSockets HTML 二进制 自定义 WebSockets&#xff1a;聊天交互较常…

Spark/Kafka

文章目录 项目地址一、Spark1. RDD1.1 五大核心属性1.2 执行原理1.3 四种创建方式二、Kafka2.1 生产者(1)分区器(2)生产者提高吞吐量(3) 生产者数据可靠性数据传递语义幂等性和事务数据有序2.2 Broker(1)Broker工作流程(2)节点服役和退役2.3 副本(1)Follower故障细…

10倍数据交付提升 | 通过逻辑数据仓库和数据编织高效管理和利用大数据

数据已经成为企业核心竞争力的关键要素。随着大数据技术的发展&#xff0c;如何高效管理和利用海量的数据&#xff0c;已成为企业在数字化转型过程中面临的重要课题。传统的数据仓库已经不能满足当今企业对数据处理的高效性、灵活性和实时性的需求。在这种背景下&#xff0c;逻…

《keras 3 内卷神经网络》

keras 3 内卷神经网络 作者&#xff1a;Aritra Roy Gosthipaty 创建日期&#xff1a;2021/07/25 最后修改时间&#xff1a;2021/07/25 描述&#xff1a;深入研究特定于位置和通道无关的“内卷”内核。 &#xff08;i&#xff09; 此示例使用 Keras 3 在 Colab 中查看 GitHub …

Unreal Engine 5 C++ Advanced Action RPG 十章笔记

第十章 Survival Game Mode 2-Game Mode Test Map 设置游戏规则进行游戏玩法 生成敌人玩家是否死亡敌人死亡是否需要刷出更多 肯定:难度增加否定:玩家胜利 流程 新的游戏模式类游戏状态新的数据表来指定总共有多少波敌人生成逻辑UI告诉当前玩家的敌人波数 3-Survival Game M…

嵌入式产品级-超小尺寸热成像相机(从0到1 硬件-软件-外壳)

Thermal_Imaging_Camera This is a small thermal imaging camera that includes everything from hardware and software. 小尺寸热成像相机-Pico-LVGL-RTOS 基于RP2040 Pico主控与RTOS&#xff0c;榨干双核性能实现LVGL和成图任务并行。ST7789驱动240280屏&#xff0c;CST8…

AI守护煤矿安全生产:基于视频智能的煤矿管理系统架构解析

前言 本文我将介绍我和我的团队自主研发设计的一款AI产品的成果展示——“基于视频AI识别技术的煤矿安全生产管理系统”。 这款产品是目前我在创业阶段和几位矿业大学的博士共同从架构设计、开发到交付的全过程中首次在博客频道发布, 我之前一直想写但没有机会来整理这套系统的…

OCCT 之 TDF_Attribute 以及子类

一.概述 TDF_Label是OCAF中核心数据结构&#xff0c;与TDF_Attribute结合使用&#xff0c;实现对模型的各种操作。 以下摘自OCCT7.7.0官方文档 A class each application has to implement. It is used to contain the application data. This abstract class, alongwith La…

数字化时代,传统代理模式的变革之路

在数字化飞速发展的今天&#xff0c;线上线下融合&#xff08;O2O&#xff09;成了商业领域的大趋势。这股潮流&#xff0c;正猛烈冲击着传统代理模式&#xff0c;给它带来了新的改变。 咱们先看看线上线下融合现在啥情况。线上渠道那是越来越多&#xff0c;企业纷纷在电商平台…

Vue2+OpenLayers添加缩放、滑块缩放、拾取坐标、鹰眼、全屏控件(提供Gitee源码)

目录 一、案例截图 二、安装OpenLayers库 三、代码实现 四、Gitee源码 一、案例截图 二、安装OpenLayers库 npm install ol 三、代码实现 废话不多说&#xff0c;直接给完整代码&#xff0c;替换成自己的KEY即可运行&#xff1a; <template><div><div i…

Vulnhub-Tr0ll靶机笔记

Tr0ll靶机笔记 概述 靶机地址&#xff1a;https://www.vulnhub.com/entry/tr0ll-1,100/ 这台靶机比较简单&#xff0c;包含ftp的渗透&#xff0c;pcap流量包的分析&#xff0c;常规的web渗透和系统内核提权。让我们开始吧 Hack it&#xff01; 一、nmap扫描 1、端口扫描 …

高效建站指南:通过Portainer快速搭建自己的在线网站

文章目录 前言1. 安装Portainer1.1 访问Portainer Web界面 2. 使用Portainer创建Nginx容器3. 将Web静态站点实现公网访问4. 配置Web站点公网访问地址4.1公网访问Web站点 5. 固定Web静态站点公网地址6. 固定公网地址访问Web静态站点 前言 Portainer是一个开源的Docker轻量级可视…

Docker Compose的使用

文章首发于我的博客&#xff1a;https://blog.liuzijian.com/post/docker-compose.html 目录 Docker Compose是什么Docker Compose安装Docker Compose文件Docker Compose常用命令案例&#xff1a;部署WordPress博客系统 Docker Compose是什么 Docker Compose是Docker官方的开源…

JDK长期支持版本(LTS)

https://blogs.oracle.com/java/post/the-arrival-of-java-23 jdk长期支持版本&#xff08;LTS&#xff09;&#xff1a;JDK 8、11、17、21&#xff1a;

python(25) : 含有大模型生成的公式的文本渲染成图片并生成word文档(支持flask接口调用)

公式样例 渲染前 \[\sqrt{1904.615384} \approx 43.64\] 渲染后 安装依赖 pip install matplotlib -i https://mirrors.aliyun.com/pypi/simple/ requestspip install sympy -i https://mirrors.aliyun.com/pypi/simple/ requestspip install python-docx -i https://mirro…