SpringBoot中使用RedisTemplate执行Redis基本命令
在application.properties或application.yml文件中配置Redis
spring: redis: host: 127.0.0.1 port: 6379
编写代码
package com.heaven.redis; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.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.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.test.context.junit4.SpringRunner; import redis.clients.jedis.Jedis; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j class RedisApplicationTests { @Autowired RedisTemplate redisTemplate; @Test void testString(){ //设置生成key value的序列化策略 RedisSerializer<String> stringSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringSerializer); redisTemplate.setValueSerializer(stringSerializer); redisTemplate.setHashKeySerializer(stringSerializer); redisTemplate.setHashValueSerializer(stringSerializer); //设值(set key value) redisTemplate.opsForValue().set("key1","value1"); //通过key取值(get key) String key1 = (String) redisTemplate.opsForValue().get("key1"); redisTemplate.opsForValue().set("key2","value2"); log.info("key1======"+key1); redisTemplate.delete("key1"); String key2 = (String) redisTemplate.opsForValue().get("key2"); log.info("key2======"+key2); //获取key对应的value的长度(strlen key) Long size = redisTemplate.opsForValue().size("key2"); log.info("size======"+size); //给key重新设值(getset key value) String getSet = (String) redisTemplate.opsForValue().getAndSet("key2", "start_value2"); log.info("getSet======"+getSet); //根据下标获取value的子串(getrange key start end) String range = redisTemplate.opsForValue().get("key2", 0, 5); log.info("range======"+range); //在value尾部添加字符(append key value) Integer end = redisTemplate.opsForValue().append("key2", "_end"); log.info("end======"+end); } }
运行结果
原文地址:https://www.cnblogs.com/heavenplus/p/11933799.html
时间: 2024-10-09 03:49:21