1. 引入Redis依赖
<!-- 引入redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 引入redis连接池的依赖 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2. 添加redis配置
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
timeout: 5000
lettuce:
pool:
max-active: 32
max-wait: -1
max-idle: 16
min-idle: 8
3. 设置redis配置类
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
4. 配置工具类,封装常用方法文章来源:https://www.toymoban.com/news/detail-709511.html
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 写入缓存
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 更新缓存
*/
public boolean getAndSet(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*/
public void removePattern(final String pattern) {
Set<String> keys = redisTemplate.keys(pattern);
if (CollectionUtils.isNotEmpty(keys)) {
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*/
public boolean exists(final String key) {
Boolean isExists = redisTemplate.hasKey(key);
return BooleanUtils.isTrue(isExists);
}
/**
* 读取缓存
*/
public Object get(final String key) {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
/**
* 哈希 添加
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
*/
public void addSet(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 删除集合下的所有值
*/
public void removeSetAll(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
Set<Object> objectSet = set.members(key);
if (objectSet != null && !objectSet.isEmpty()) {
for (Object o : objectSet) {
set.remove(key, o);
}
}
}
/**
* 判断set集合里面是否包含某个元素
*/
public Boolean isMember(String key, Object member) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.isMember(key, member);
}
/**
* 集合获取
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*/
public void zAdd(String key, Object value, double source) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, source);
}
/**
* 有序集合获取指定范围的数据
*/
public Set<Object> rangeByScore(String key, double source, double source1) {
ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
return zSet.rangeByScore(key, source, source1);
}
/**
* 有序集合升序获取
*/
public Set<Object> range(String key, Long source, Long source1) {
ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
return zSet.range(key, source, source1);
}
/**
* 有序集合降序获取
*/
public Set<Object> reverseRange(String key, Long source, Long source1) {
ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
return zSet.reverseRange(key, source, source1);
}
}
5. 编写测试类文章来源地址https://www.toymoban.com/news/detail-709511.html
import com.alibaba.fastjson.JSON;
import com.maple.demo.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/example")
@Api(tags = "实例演示-Redis接口文档")
public class TestRedisController {
private final RedisUtil redisUtil;
@PutMapping("/insertStr")
@ApiOperation(value = "插入String类型的数据到redis")
public void insertStr(String key, String value) {
redisUtil.set(key, value);
}
@PostMapping("/getStr")
@ApiOperation(value = "根据key获取redis的数据")
public String getStr(String key) {
return String.valueOf(redisUtil.get(key));
}
@DeleteMapping("/deleteStr")
@ApiOperation(value = "根据key删除redis的数据")
public Boolean deleteStr(String key) {
redisUtil.remove(key);
return redisUtil.exists(key);
}
@PostMapping("/operateMap")
@ApiOperation(value = "模拟操作Map集合的数据")
public Object operateMap() {
redisUtil.hmSet("maple:map", "xiaofeng", "笑小枫");
return redisUtil.hmGet("maple:map", "xiaofeng");
}
@PostMapping("/operateList")
@ApiOperation(value = "模拟操作List集合的数据")
public String operateList() {
String listKey = "maple:list";
redisUtil.lPush(listKey, "1");
redisUtil.lPush(listKey, "2");
redisUtil.lPush(listKey, "3");
return JSON.toJSONString(redisUtil.lRange(listKey, 0, 2));
}
@PostMapping("/operateSet")
@ApiOperation(value = "模拟操作Set集合的数据")
public String operateSet() {
String listKey = "maple:set";
redisUtil.addSet(listKey, "小枫");
redisUtil.addSet(listKey, "小明");
redisUtil.addSet(listKey, "小枫");
log.info("集合中是否包含小枫" + redisUtil.isMember(listKey, "小枫"));
log.info("集合中是否包含小红" + redisUtil.isMember(listKey, "小红"));
return JSON.toJSONString(redisUtil.setMembers(listKey));
}
@PostMapping("/operateZSet")
@ApiOperation(value = "模拟操作ZSet有序集合的数据")
public String operateZSet() {
String listKey = "maple:zSet";
redisUtil.zAdd(listKey, "小枫", 8);
redisUtil.zAdd(listKey, "小明", 1);
redisUtil.zAdd(listKey, "小红", 12);
redisUtil.zAdd(listKey, "大明", 5);
redisUtil.zAdd(listKey, "唐三", 10);
redisUtil.zAdd(listKey, "小舞", 9);
// 降序获取source最高的5条数据
return JSON.toJSONString(redisUtil.reverseRange(listKey, 0L, 4L));
}
}
到了这里,关于SpringBoot中引入Redis的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!