SpringBoot整合Redis 记录

本文介绍了如何在Spring Boot项目中整合Redis,通过pom.xml添加依赖,配置application.yml文件,然后展示了测试代码,包括对Redis的String、Hash、List、Set、SortedSet操作。在测试时遇到了无法连接到Redis服务器的问题,解决方法是确保Redis服务已正确启动和配置。

 

1.在pom.xml文件中添加如下依赖

<!--整合Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
 

2.配置application.yml文件

spring:
  profiles:
    active: abc,def

  #把JdbcConfig 类中的druid的配置删除或注释
  #在刚才引入jdbc启动器的时候,SpringBoot已经自动帮我们引入了一个连接池,HikariCP应该是目前速度最快的连接池
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: root

  redis:
    host: localhost
    port: 6379
    timeout: 10000

 

3.编写测试代码时遇到的问题

package com.itheima.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Set;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){

        //string字符串
        redisTemplate.opsForValue().set("str", "xxx");
        redisTemplate.boundValueOps("str").set("xxx");
        System.out.println("str = " + redisTemplate.opsForValue().get("str"));
        // hash散列
        redisTemplate.boundHashOps("h_key").put("name", "xxx");
        redisTemplate.boundHashOps("h_key").put("age", 13);

        //获取所有域对应的值
        Set set = redisTemplate.boundHashOps("h_key").keys();
        System.out.println("hash散列所有的域:" + set);
        List list = redisTemplate.boundHashOps("h_key").values();
        System.out.println("hash散列所有的域值:" + list);

        //list列表
        redisTemplate.boundListOps("l_key").leftPush("c");
        redisTemplate.boundListOps("l_key").leftPush("b");
        redisTemplate.boundListOps("l_key").leftPush("a");
        list = redisTemplate.boundListOps("l_key").range(0, -1);
        System.out.println("列表的值:" + list);

        //set集合
        redisTemplate.boundSetOps("set_key").add("a", "b", "c");
        set = redisTemplate.boundSetOps("set_key").members();
        System.out.println("集合的元素:" + set);

        //sorted set有序集合
        redisTemplate.boundZSetOps("z_key").add("a", 30);
        redisTemplate.boundZSetOps("z_key").add("b", 20);
        redisTemplate.boundZSetOps("z_key").add("c", 10);
        set = redisTemplate.boundZSetOps("z_key").range(0, -1);
        System.out.println("有序集合的元素:" + set);
    }
}

 

4.测试问题

org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379

 

(1)启动命令

redis-server redis.windows.conf

 

(2)设置服务命令

redis-server --service-install redis.windows-service.conf --loglevel verbose

 

(3)常用Redis服务命令

卸载服务:redis-server --service-uninstall

开启服务:redis-server --service-start

停止服务:redis-server --service-stop

 

(4)优质Redis文章

https://www.cnblogs.com/yunqing/p/10605934.html  安装

https://blog.youkuaiyun.com/qian_qian_123/article/details/85161320   用法

https://blog.youkuaiyun.com/lei396601057/article/details/77527061    服务

 

 

### Spring Boot 整合 Redis 的配置与使用 #### 1. 添加依赖 为了使 Spring Boot 应用程序能够访问 Redis 数据库,在 `pom.xml` 文件中加入必要的 Maven 依赖项。这通常涉及添加 Spring Data Redis 和 Lettuce 客户端驱动作为构建工具的一部分。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 如果需要支持Redis哨兵模式 --> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` #### 2. 配置 Redis 连接属性 编辑应用程序的主要配置文件 (`application.properties`) 来指定目标 Redis 实例的位置和其他连接选项: ```properties spring.redis.sentinel.master=mymaster spring.redis.sentinel.nodes=192.168.1.1:26379,192.168.1.2:26379,192.168.1.3:26379 spring.redis.database=0 spring.redis.timeout=6000 ``` 这些设置指定了要使用的主节点名称以及一组监视该主节点的哨兵地址列表[^1]。 #### 3. 自定义 Redis 配置类 创建一个新的 Java 类,比如命名为 `RedisConfig.java`, 并在此处定义所需的 bean 方法来初始化 `RedisSentinelConfiguration` 及其关联的工厂对象 `LettuceConnectionFactory`. 此外还需实例化一个通用型别的 `RedisTemplate<String,Object>` 对象以便后续业务逻辑层调用. ```java @Configuration public class RedisConfig { @Bean public RedisSentinelConfiguration redisSentinelConfiguration() { Set<String> sentinels = new HashSet<>(); String[] sentinelNodesArray = env.getProperty("spring.redis.sentinel.nodes").split(","); Collections.addAll(sentinels, sentinelNodesArray); RedisSentinelConfiguration config = new RedisSentinelConfiguration() .master(env.getProperty("spring.redis.sentinel.master")) .sentinels(sentinels); return config; } @Bean public LettuceConnectionFactory lettuceConnectionFactory(RedisSentinelConfiguration configuration) { return new LettuceConnectionFactory(configuration); } @Bean(name="redisTemplate") public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory){ final RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashValueSerializer(template.getValueSerializer()); template.setConnectionFactory(connectionFactory); return template; } } ``` 这段代码片段展示了如何通过编程方式设定哨兵集群的相关参数,并且设置了序列化器以确保键值对能被正确处理和解析. #### 4. 使用 RedisTemplate 执行 CRUD 操作 一旦完成了前面几步的工作之后就可以轻松地利用注入好的 `RedisTemplate` 资源来进行各种读写命令了: ```java @Service public class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); private final RedisTemplate<String, Object> redisTemplate; @Autowired public MyService(@Qualifier("redisTemplate") RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } // 存储字符串类型的简单例子 public void setString(String key, String value) { ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue(); opsForValue.set(key, value); logger.info("Set {} to {}", key, value); } // 获取之前保存过的字符串 public String getString(String key) { ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue(); return (String)opsForValue.get(key); } } ``` 此部分提供了基本的操作模板,包括但不限于设置单个条目、获取已存在的记录等基础功能[^2].
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值