<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
redis:
cluster:
nodes: 127.0.0.1:9001,127.0.0.1:9002,127.0.0.1:9003
password: ******
timeout: 10000ms
database: 0
jedis:
pool:
max-idle: 8
min-idle: 1
max-active: 8
max-wait: 6000ms
这里我们使用了 jedis 连接池。
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);
@Override
public void setStr(String key, String value) {
logger.info("插入 Redis 数据。入参:key:{},value:{}", key, value);
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.set(key, value);
}
@Override
public String getStr(String key) {
logger.info("获取 Redis 数据。入参:key:{}", key);
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
String value = operations.get(key);
logger.info("获取 Redis 数据。出参:value:{}", value);
return value;
}
@Override
public void delStr(String key) {
logger.info("删除 Redis 数据。入参:key:{}", key);
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.getOperations().delete(key);
}
操作 Redis 的主要类是 stringRedisTemplate
,这个类可以获取不同类型的 Redis操作对象。
Stirng 类型:stringRedisTemplate.opsForValue()
List 类型:stringRedisTemplate.opsForList()
Set 类型:stringRedisTemplate.opsForSet()
Hash 类型:stringRedisTemplate.opsForHash()
可以看到,opsForXXX() 不能删除 Redis 中的key,这个时候可以使用下面的方法,获取RedisOperations
对象。通过该对象进行一些 Redis 的操作。
opsForHash().getOperations().delete(key);
我们针对这个 Service 写个单元测试,测试一下
@RunWith(SpringRunner.class)
@SpringBootTest()
public class RedisServiceImplTest {
@Autowired
private RedisService redisService;
@Test
public void setStr() throws Exception {
redisService.setStr("TEST","1234");
}
@Test
public void getStr() throws Exception {
System.out.println(redisService.getStr("TEST"));
}
@Test
public void delStr() throws Exception {
redisService.delStr("TEST");
}
}