springboot 搭建一个 测试redis 集群连通性demo

7 篇文章 0 订阅
1 篇文章 0 订阅

背景:我需要用 springboot 建一个测试 redis 集群连通性的 demo
废话不多说直接上代码:
1.pom

</dependency>
			<!-- Spring Boot Starter Data Redis -->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-data-redis</artifactId>
			</dependency>
			<!-- Jedis Client for cluster support -->
			<dependency>
				<groupId>redis.clients</groupId>
				<artifactId>jedis</artifactId>
			</dependency>

2.配置

spring:
  application:
    name: demo
  redis:
    cluster:
      nodes:
        - 10.228.48.28:26379,10.228.48.19:26379,
        - 10.228.48.21:26379,10.228.48.28:26380,
        - 10.228.48.19:26380,10.228.48.21:26380
    password: 0666AAcuSl_VLC8e
    timeout: 10000
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0



3.建一个 config 类

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author wangjn
 * @Description
 * @createTime 2024-06-13 10:44:00
 */
@Service
public class RedisClusterService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void setValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

4.controller

package com.example.demo;

import com.example.demo.config.RedisClusterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author wangjn
 * @Description
 * @createTime 2024-06-13 10:49:00
 */
@RestController
public class RedisController {

    @Autowired
    private RedisClusterService redisClusterService;

    // 设置Redis键值对
    @PostMapping("/redis/set/{key}")
    public String setValue(@PathVariable("key") String key, @RequestBody String value) {
        redisClusterService.setValue(key, value);
        return "Value set successfully for key: " + key;
    }

    // 获取Redis中的值
    @GetMapping("/redis/get/{key}")
    public String getValue(@PathVariable("key") String key) {
        return redisClusterService.getValue(key);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值