server.port=80
server.servlet.context-path=/
#reids相关配置
#redis服务器地址
spring.redis.host=localhost
#雷迪森服务器端口
spring.redis.port=6379
#redis密码,默认为空
spring.redis.password=
#redis数据库索引(默认为0)
spring.redis.database=0
#连接池对打阻塞等待时间(负表示没有限制)
spring.redis.jedis.pool.max-wait=10000
#连接池最大连接数(负表示没有限制)
spring.redis.jedis.pool.max-active=100
#连接池中的最大空闲链接
spring.redis.jedis.pool.max-idle=20
#连接池中的最小空闲链接
spring.redis.jedis.pool.min-idle=0
#链接超时时间
spring.redis.timeout=3000
测试链接
1、测试
在RedisDemoApplicationTests测试类中,编写代码测试连接。
测试代码如下:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class RedisDemoApplicationTests {
@Autowired
private RedisTemplate
@Test
void contextLoads() {
//向redis中添加数据
redisTemplate.opsForValue().set(“keys”, “value值”);
//根据键值取出数据
System.out.println(redisTemplate.opsForValue().get(“keys”));
}
}
【释】 RedisTemplate是Spring Data Redis提供给用户的最高级的抽象客户端,用户可直接通过RedisTemplate对redis进行操作。操作方法即redis的指令,关于redis的指令的操作可以移步:Redis数据类型及基本使用。
可以点进去看一下RedisTemplate继承关系和方法,下面是继承关系,方法就比较多了,这里就不贴出来了,感兴趣的小伙伴可以直接去RedisTemplate类中看看。
//RedisAccessor是RedisTemplate定义普通属性的基类,不直接使用
//RedisOperations是指定RedisTemplate实现的Redis connection操作的集合接口
//BeanClassLoaderAware是给其实现类是设置类加载器的接口
RedisTemplate
【注】 上述的测试案例中RedisTemplate中的value值设置的是String类型,但redis有五种数据类型,所以这里最好使用Object类型。
@Resource
private RedisTemplate
这里注解如果继续使用@AutoWired会报错,需要使用@Resource,这两个注解的区别在前者是根据类型后者是根据名字(报错原因:@AutoWired找不到该类型
操作不同类型的数据,调用的方法不同
-
操作String字符串类型数据时,使用RedisTemplate类中的opsForValue方法操作。
-
操作List列表类型数据时,使用RedisTemplate类中的opsForList方法操作。
-
操作Set集合类型数据时,使用RedisTemplate类中的opsForSet方法操作。
-
操作Hash哈希类型数据时,使用RedisTemplate类中的opsForHash方法操作。
-
操作Zset有序集合类型数据时,使用RedisTemplate类中的opsForZSet方法操作。
查看Redis中的数据,可以使用RedisDesktopManager工具查看。
Springboot整合Redis使用
上述操作可以直接在Springboot项目中使用。但也可以对redisTemplate的操作进行一下简单的封装。
1、Redis配置类Redis配置类RedisConfig类代码如下:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate
RedisTemplate
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
@Bean
public HashOperations
return redisTemplate.opsForHash();
}
@Bean
public ValueOperations
return redisTemplate.opsForValue();
}
@Bean
public ListOperations
return redisTemplate.opsForList();
}
@Bean
public SetOperations
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations
return redisTemplate.opsForZSet();
}
}
2、RedisTemplate封装RedisTemplate封装工具类代码如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate
public RedisUtil(RedisTemplate
this.redisTemplate = redisTemplate;
}
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings(“unchecked”)
public void del(String … key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//String=
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException(“递增因子必须大于0”);
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException(“递减因子必须大于0”);
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//Map=
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
public Map
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object… item){
redisTemplate.opsForHash().delete(key,item);
}
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}
//set=
public Set sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sSet(String key, Object…values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key,long time,Object…values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object …values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//=list===
public List lGet(String key, long start, long end){
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSetList(String key, List value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
-
将list放入缓存
-
@param key 键
-
@param value 值



