一、Redis简介
Redis(Remote Dictionary Server) 是一个使用 C 语言编写的,开源的(BSD许可)高性能非关系型(NoSQL)的键值对数据库。
优势:读写速度非常快;因为对redis的操作完全基于内存,绝大部分请求是纯粹的内存操作,非常快速。数据存在内存中,类似于HashMap,HashMap 的优势就是查找和操作的时间复杂度都是O(1);
二、Redis整合到Springboot项目
2.1、添加maven依赖
spring-boot-starter-data-redis
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.5</version>
</dependency>
springboot项目的redis依赖在maven仓库地址:https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis
2.2、redis配置信息(application.properties)
# Redis服务器地址(必配置)
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# Redis数据库索引(默认为0)
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000ms
2.3、配置类(RedisConfig.class)
在使用RedisTemplate之前,还需要配置序列规则,不然存到redis中的k和v都是16进制乱码。因为redis默认使用JdkSerializationRedisSerializer(jdk自己的序列化)。
如果不配置的话,当你@Authwired RedisTemplate edisTemplate的时候,就会使用默认的jdk序列。
参考我另一篇博客:https://blog.csdn.net/TAaron666/article/details/116789521
配置类代码:
package com.tzq.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @Author tangzhiqian
* @CreateTime 2021/5/14 13:15
*/
@Configuration
public class RedisConfig {
@Bean
RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());//支持直接序列化对象
return redisTemplate;
}
}
三、RedisTemplate常用方法
经过上面的配置,我们已经可以在项目中使用redis了。在springboot项目中主要通过RedisTemplate这个类来操作redis,下面详细介绍RedisTemplate的常用 方法:
3.1 存储数据:
String类存储:
redisTemplate.opsForValue( ).set(key,value)
Hash类数据存储:
redisTemplate.opsForHash( ).set(key,hashKey,value)
List链表类存储:
redisTemplate.opsForList().leftPush(key ,value);
redisTemplate.opsForList().rightPush(key,value);
如果没有才set,返回值:Boolean类型,设置成功了为True:
redisTemplate.opsForValue( ).setIfAbsent(key,value)
3.2 获取数据:
String类存储:
redisTemplate.opsForValue( ).get(key)
Hash类数据存储:
redisTemplate.opsForHash( ).value(key)
List链表类存储:
redisTemplate.opsForList().leftPop(key);
redisTemplate.opsForList().rightPop(key);
3.3 过期时间
根据key设置过期时间:
// 多久后过期
redisTemplate.expire(KEY_HEAD+"hash",100, TimeUnit.MINUTES);
// 到什么日期过期
redisTemplate.expireAt(KEY_HEAD+"hash",new Date(2021,10,8,1,1,1));
除此之外,还可以在设置value的同时设置过期时间。
四、利用redis实现分布式锁(待完善)
redis实现分布式锁,实现原理主要依靠该方法:setIfAbsent(key,value)。
加锁:
package com.park.lock.impl;
import com.park.lock.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class RedisLock {
@Autowired
private RedisTemplate redisTemplate;
public boolean lock(String key,String value){
if(redisTemplate.opsForValue().setIfAbsent(key,value)){//setNX 返回boolean
return true;
}
String currentValue = redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue)<System.currentTimeMillis()){
String oldvalue = redisTemplate.opsForValue().getAndSet(key,value);
if(!StringUtils.isEmpty(oldvalue)&&oldvalue.equals(currentValue)){
return true;
}
}
return false;
}
@Override
public void unlock(String key) {
redisTemplate.opsForValue().getOperations().delete(key);
}
}
解锁:
本文详细介绍了如何将Redis整合到SpringBoot项目中,包括添加maven依赖、配置redis连接信息以及编写RedisConfig配置类。重点讨论了RedisTemplate的常用操作,如存储和获取数据,设置过期时间,并展示了使用RedisTemplate实现分布式锁的简单示例。

1443

被折叠的 条评论
为什么被折叠?



