前言:给同学们推荐第二首歌 《你曾是少年》S.H.E
首先,我们需要了解一下 redis 是什么,有什么用处,在哪里用
redis:redis 是一种基于内存的非关系型的 key value 的数据库,也就是 NoSQL技术。在 NoSQL 中使用最广泛的是 redis 和 mongoDB,redis 支持每秒几十万的读写操作,性能远超数据库库,且还支持集群、分布式等,还支持一定的事务能力,保证了噶奥并发的场景下数据的安全性和一致性。
有什么用处:在实际运用中,对数据库的读操作远远多于写操作,在读的时候,需要用sql语句去操作数据库,数据库把对应的数据索引取回来,这是一个相对而言较慢的过程。但是如果我们把数据存放在内存中,这样服务器就会直接去内存中取数据,会很大程度上提升速度,而且减少了数据库的负担,但是使用内存存储数据库对内存开销比较大,所以我们一般只存放用户信息等这些小体积的数据。
在哪里用:商品抢购、主页数据等这些数据一瞬间爆发的业务场景。
注:关于 redis 的安装、具体介绍以及特点各位官人请移步
https://www.jianshu.com/p/56999f2b8e3b
测试 Demo:https://github.com/XGLLHZ/springboot-frame frame-util
1、在 pom.xml 文件中加入 redis 依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在 yml 文件中加入 redis 的基本参数配置
spring:
redis: #redis数据库配置
database: 0 #数据库索引,默认为0
host: localhost #地址
port: 6379 #端口号,默认为6379
password: #密码,默认为空
jedis:
pool:
max-active: 8 #连接池最大连接数(负值表示没有限制)
max-wait: -1 #连接池最大阻塞时间(复制表示没有限制)
max-idle: 8 #连接池中的最大空闲连接
min-idle: 0 #连接池中的最小空闲连接
timeout: 5000 #连接超时时间(毫秒)
3、redis 配置文件
注:1、springboot 为我们提供了自动生成 RedisTemplate 的作用,但是其生成的泛型是 <Object, Object>,而我们日常开发中使用的是 <String, Object>。2、springboot 生成的 RedisTemplate 在存数据时没有对 key 进行序列化,这不符合我们一般的开发规范。这两点就是我们配置 RedisTemplate 的原因。
@Configuration
@EnableCaching #开启注解
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//配置连接工厂
template.setConnectionFactory(factory);
//使用 Jackson 来序列化和反序列化 redis 的 value 值(默认使用 JDK 的序列化方法)
Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//使用 String 来序列化 redis 的 key 值
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
ObjectMapper objectMapper = new ObjectMapper();
//指定序列化的域,field、get、set,以及修饰范围,ANY 是都包括
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//指定序列化输入的类型,必须是 final 修饰的
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jsonRedisSerializer.setObjectMapper(objectMapper);
//序列化
//序列化 key
template.setKeySerializer(stringRedisSerializer);
//序列化 value
template.setValueSerializer(jsonRedisSerializer);
//序列化 hash 的 key
template.setHashKeySerializer(stringRedisSerializer);
//序列化 hash 的 key
template.setHashValueSerializer(jsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4、redis 工具类
为了减少代码的编写量,所以我们给它整个工具类,来操作 redis 。比如一般数据存放,获取、对 map 的存放获取、对 list 的存放获取以及各种过期时间的操作等。
@Component
public class RedisUtil {
@Autowired
public RedisTemplate<String, Object> redisTemplate;
/**
* 判断 key 是否存在
* @param key
* @return
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除 key
* @param key 可传一个,也可传多个
*/
public void deleteKey(String... key) {
if (key != null && key.length > 0) {
redisTemplate.delete(Arrays.asList(key));
}
}
/**
* 设置缓存过期时间
* @param key
* @param time
* @return
*/
public boolean setTime(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获取缓存过期时间
* @param key
* @return
*/
public long getTime(String key) {
return key == null ? null : redisTemplate.getExpire(key);
}
/**
* 存入
* @param key
* @param object
* @return
*/
public boolean setValue(String key, Object object) {
try {
redisTemplate.opsForValue().set(key, object);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获取
* @param key
* @return
*/
public Object getValue(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 存入并设置过期时间
* @param key
* @param object
* @param time 秒,若 time > 0,则为无限期
* @return
*/
public boolean setValue(String key, Object object, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, object, time);
} else {
setValue(key, object);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 存入 list
* @param key
* @param value
* @return
*/
public boolean setListValue(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获取 list
* @param key
* @param start
* @param end
* @return
*/
public List<Object> getListVaule(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 存入 list 并设置时间
* @param key
* @param value
* @param time
* @return
*/
public boolean setListValue(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
setTime(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
注:之前我想着把工具类中的方法都定义为静态的,但是 后来报错了,查了一下才知道,在 spring 中注入的时候不能注入静态类,因为 spring 注入实际上是在容器内实例化对象,而静态类不需要实例化对象。
5、测试
实体类:
@Data
@Accessors(chain = true)
public class TestEntity implements Serializable {
private Integer id;
private String testName;
private String testMessage;
}
操作:
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
RedisUtil redisUtil;
@RequestMapping("/test")
public void set() {
TestEntity testEntity = new TestEntity();
testEntity.setId(1);
testEntity.setTestName("guohao");
testEntity.setTestMessage("人世间子");
boolean result = redisUtil.setValue("guohao", testEntity);
TestEntity testEntity1 = (TestEntity) redisUtil.getValue("guohao");
System.out.println("将要存入的数据是:" + testEntity.getId() + "," +
testEntity.getTestName() + "," + testEntity.getTestMessage());
System.out.println("是否正常存入:" + result);
System.out.println(testEntity1 == null ? "是否正常取出:false" : "是否正常取出:true");
System.out.println("取出的数据是:" + testEntity1.getId() + "," +
testEntity1.getTestName() + "," + testEntity1.getTestMessage());
}
}
结果:
各位官人立冬了!