【Redis】Hash结构操作

在基础篇的最后,咱们对Hash结构操作一下,收一个小尾巴。

opsForValue() 拿到的是对字符串的操作,opsForHash() 拿到的就是跟哈希有关的操作。

PS:在spring中并不是以命令作为方法名,方法名类似于Java的HashMap的方法名。

hashKey和value就是对应字段和字段值,事实上value中可能会有多个字段,一个 put() 只能存一个字段,如果有多个字段,put() 就需要执行多次,这样其实就不太好了,等于你是与服务器做多次交互。

因此推荐大家的方案是使用 putAll()putAll() 相当于 hmset,里面可以存好几个键值对。

image-20240524072528015

@SpringBootTest
class RedisStringTests {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    void testHash() {
        stringRedisTemplate.opsForHash().put("user:400", "name", "虎哥");
        stringRedisTemplate.opsForHash().put("user:400", "age", "21");

        // 取一个字段是get方法,取好多字段是entries方法,Java是entrySet方法,也是类似的。
        // values方法就是获取里面的值
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:400");
        System.out.println("entries = " + entries);
    }
}

运行代码,可以发现插入成功

image-20240524073051097

Redis Hash 结构是一种数据结构,它允许你将键值对存储为哈希表的形式,其中每个键都是唯一的,并且可以关联任意类型的数据(包括字符串、列表、集合或有序集合)。在 Spring Boot 中整合 Redis,你可以使用 Spring Data Redis 库,它简化了与 Redis 的交互。 Spring Boot 整合 Redis 的步骤如下: 1. 添加依赖:在你的 `pom.xml` 或 `build.gradle` 文件中添加 Spring Data Redis 和相关 Redis客户端库的依赖,如 lettuce 或 Jedis。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- Gradle (Lettuce) --> implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.5.x' implementation 'io.lettuce:lettuce-core:6.0.x' ``` 2. 配置 Redis:在 `application.properties` 或 `application.yml` 中配置 Redis 的连接信息,如主机名、端口和密码(如果有)。 ```yaml spring.redis.host=your-redis-host spring.redis.port=your-redis-port spring.redis.password=your-password ``` 3. 使用 `HashOperations`:Spring Data Redis 提供了 `HashOperations` 接口,你可以通过注入 `RedisTemplate` 或 `HashOperations` 对象来操作 RedisHash 结构。 ```java @Autowired private RedisTemplate<String, Object> redisTemplate; // 使用方法 HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash("your-hash-key"); hashOps.put("field1", "value1"); hashOps.get("field1"); // 获取 value1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值