参考:https://blog.csdn.net/n950814abc/article/details/94199597
所以需要我们对key值进行一定的分类:
使用“:”冒号来体现层次。
代码:
package com.example.dtest.redis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/*
* 参考:http://www.redis.cn/
* Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。
* 它支持多种类型的数据结构,
* 如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets)
* 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),
* LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence)
* , 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。
* */
@Slf4j
@Component
public class RedisTestMethod {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
/*---------------------------1:redis有五种数据类型 opsForValue表示是操作字符串类型-------------------------*/
/*--------增加:-------*/
//本来只可以放入string类型,但是我们配置了自动序列化所以这儿可以传入object
public boolean setValue(String key,Object value){
try{
redisTemplate.opsForValue().set(key,value);
return true;
}catch (Exception e){
log.error("redis set value exception:{}",e);
return false;
}
}
/*--------增加:指定保存时间-------*/
public boolean setValueByTime(String key,Object value,long expire){
try{//TimeUnit.SECONDS指定类型为秒
redisTemplate.opsForValue().set(key,value,expire, TimeUnit.SECONDS);
return true;
}catch (Exception e){
log.error("redis set value and expire exception:{}",e);
return false;
}
}
// 通过主键查询
private String getRedisValue(String key,RedisTemplate redisTemplate){
return null;
}
}
package com.example.dtest.redisTest;
import com.example.dtest.DtestApplication;
import com.example.dtest.redis.RedisTestMethod;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = DtestApplication.class)
public class RedisTest {
@Autowired
RedisTestMethod redisTestMethod;
@Test
void test01(){
redisTestMethod.setValue("a:234", "456");
}
}
设置redis在指定数据库里面;
#redis
redis:
# redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突,通过rdm查看时,在db3的下面
database: 1