springboot在redis里存放list并获取指定value

@Autowired
private StringRedisTemplate redisTemplate;
@Test
    public void testRedisList() {
        redisTemplate.opsForList().rightPush("list", "one");
        redisTemplate.opsForList().rightPush("list", "two");
        redisTemplate.opsForList().rightPush("list", "three");
        redisTemplate.opsForList().rightPush("list", "four");
        List<String> list4 = redisTemplate.opsForList().range("list4", 0, -1);
        System.out.println(redisTemplate.opsForList().index("list", 0));
        System.out.println(redisTemplate.opsForList().index("list", 1));
        System.out.println(redisTemplate.opsForList().index("list", 2));
        System.out.println(redisTemplate.opsForList().index("list", 3));
        System.out.println(redisTemplate.opsForList().index("list", 4));
        System.out.println(redisTemplate.opsForList().index("list", -1));
    }

 

输出

one

two

three

four

null

four

 

index(K key, long index)

 获取集合指定位置的值。

index("list", -1)获取的是最后一个value,index不存在输出null

 

 

 

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 整合 Redis 操作 list 集合需要使用 RedisTemplate 或 StringRedisTemplate 进行操作。下面是一个简单的示例代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.List; @Service public class RedisListService { @Autowired private RedisTemplate<String, String> redisTemplate; // 向 list 集合中添加元素 public void addToList(String key, String value) { redisTemplate.opsForList().rightPush(key, value); } // 获取 list 集合中的所有元素 public List<String> getList(String key) { return redisTemplate.opsForList().range(key, 0, -1); } // 获取 list 集合中指定范围的元素 public List<String> getListRange(String key, int start, int end) { return redisTemplate.opsForList().range(key, start, end); } // 获取 list 集合中指定索引位置的元素 public String getListIndex(String key, int index) { return redisTemplate.opsForList().index(key, index); } // 获取 list 集合中元素数量 public long getListSize(String key) { return redisTemplate.opsForList().size(key); } // 从 list 集合中删除元素 public void removeFromList(String key, String value) { redisTemplate.opsForList().remove(key, 0, value); } } ``` 上述代码中,我们使用了 `RedisTemplate` 或 `StringRedisTemplate` 中的 `opsForList` 方法来操作 list 集合,具体操作包括: - `rightPush`:向 list 集合右侧添加元素 - `range`:获取 list 集合中的所有元素或者指定范围的元素 - `index`:获取 list 集合中指定索引位置的元素 - `size`:获取 list 集合中元素数量 - `remove`:从 list 集合中删除元素 你可以根据自己的实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值