SpringBoot2.X整合Redis
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
项目采用SpringBoot2.3.3
项目目录
pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.3.RELEASEversion>
<relativePath/>
parent>
<groupId>net.auiogroupId>
<artifactId>spring-boot-redisartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>spring-boot-redisname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
<springboot.version>2.2.3.RELEASEspringboot.version>
<fastjson.version>1.2.54fastjson.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<version>${springboot.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>${fastjson.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<fork>truefork>
configuration>
plugin>
plugins>
build>
project>
application.properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=500
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=0
RedisConfig.java
package net.auio.springboot.config;
import net.auio.springboot.Initializr.MyRedisSerInitializr;
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.StringRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate
redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate
template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
MyRedisSerInitializr myRedisSerInitializr = new MyRedisSerInitializr();
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(myRedisSerInitializr);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(myRedisSerInitializr);
return template;
}
}
RedisController.java
package net.auio.springboot.controller;
import net.auio.springboot.exception.BusinessException;
import net.auio.springboot.service.RedisService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
public class RedisController {
RedisService redisService;
public String getvalue( String key){
if (!StringUtils.isEmpty(key)){
if(!redisService.hasKey(key)){
return "key不存在";
}
Object o = redisService.get(key);
return o.toString();
}else{
return "key不允许为空";
}
}
public String addStringRedis(String key,String value){
try {
redisService.set(key,value);
return key+"添加成功";
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(1001,e.getMessage());
}
}
}
BusinessException.java
package net.auio.springboot.exception;
public class BusinessException extends RuntimeException {
private final int messageCode;
private final String detailMessage;
public BusinessException(int messageCode,String message){
super(message);
this.messageCode=messageCode;
this.detailMessage =message;
}
public int getMessageCode() {
return messageCode;
}
public String getDetailMessage() {
return detailMessage;
}
}
MyRedisSerInitializr.java
package net.auio.springboot.Initializr;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class MyRedisSerInitializr implements RedisSerializer<Object> {
private final Charset charset;
public MyRedisSerInitializr() {
this(StandardCharsets.UTF_8);
}
public MyRedisSerInitializr(Charset charset) {
this.charset = charset;
}
public byte[] serialize(Object o) throws SerializationException {
if(o==null){
return new byte[0];
}
if (o instanceof String){
return o.toString().getBytes(charset);
}else {
String string=JSON.toJSONString(o);
return string.getBytes(charset);
}
}
public Object deserialize(byte[] bytes) throws SerializationException {
return (bytes==null ? null : new String(bytes,charset));
}
}
RedisService.java
package net.auio.springboot.service;
import net.auio.springboot.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class RedisService {
private RedisTemplate
redisTemplate; /** -------------------key相关操作--------------------- */
/**
* 是否存在key
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
* @return java.lang.Boolean
* @throws
*/
public Boolean hasKey(String key) {
if (null==key){
return false;
}
return redisTemplate.hasKey(key);
}
/**
* 删除key
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
* @return Boolean 成功返回true 失败返回false
* @throws
*/
public Boolean delete(String key) {
if (null==key){
return false;
}
return redisTemplate.delete(key);
}
/**
* 批量删除key
* @Author: 妖妖玖
* @CreateDate: 2019/8/27 20:27
* @UpdateUser:
* @UpdateDate: 2019/8/27 20:27
* @Version: 0.0.1
* @param keys
* @return Long 返回成功删除key的数量
* @throws
*/
public Long delete(Collection
keys) { return redisTemplate.delete(keys);
}
/**
* 设置过期时间
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
• * @param timeout
• * @param unit
* @return java.lang.Boolean
* @throws
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {
if (null==key||null==unit){
return false;
}
return redisTemplate.expire(key, timeout, unit);
}
/**
* 查找匹配的key
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param pattern
* @return java.util.Set
* @throws
*/
public Set
keys(String pattern) { if (null==pattern){
return null;
}
return redisTemplate.keys(pattern);
}
/**
* 移除 key 的过期时间,key 将持久保持
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
* @return java.lang.Boolean
* @throws
*/
public Boolean persist(String key) {
if (null==key){
return false;
}
return redisTemplate.persist(key);
}
/**
* 返回 key 的剩余的过期时间
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
• * @param unit
* @return java.lang.Long 当 key 不存在时,返回 -2 。当 key 存在但没有设置剩余生存时间时,返回 -1 。否
则,以秒为单位,返回 key的剩余生存时间
* @throws
*/
public Long getExpire(String key, TimeUnit unit) {
if(null==key||null==unit){
throw new BusinessException(4001004,"key or TomeUnit 不能为空");
}
return redisTemplate.getExpire(key, unit);
}
//*************String相关数据类型***************************
/**
* 设置指定 key 的值
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
• * @param value
* @return void
* @throws
*/
public void set(String key, Object value) {
if(null==key||null==value){
return;
}
redisTemplate.opsForValue().set(key, value);
}
/**
* 设置key 的值 并设置过期时间
* @Author: 妖妖玖
迎学教育
* @UpdateUser:
* @Version: 0.0.1
* @param key
• * @param value
• * @param time
• * @param unit
* @return void
* @throws
*/
public void set(String key,Object value,long time,TimeUnit unit){
if(null==key||null==value||null==unit){
return;
}
redisTemplate.opsForValue().set(key,value,time,unit);
}
/**
* 设置key 的值 并设置过期时间
* key存在 不做操作返回false
* key不存在设置值返回true
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
• * @param value
• * @param time
• * @param unit
* @return java.lang.Boolean
* @throws
*/
public Boolean setifAbsen(String key,Object value,long time,TimeUnit unit){
if(null==key||null==value||null==unit){
throw new BusinessException(4001004,"kkey、value、unit都不能为空");
}
return redisTemplate.opsForValue().setIfAbsent(key,value,time,unit);
}
/**
* 获取指定Key的Value。如果与该Key关联的Value不是string类型,Redis将抛出异常,
* 因为GET命令只能用于获取string Value,如果该Key不存在,返回null
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
* @return java.lang.Object
* @throws
*/
public Object get(String key){
if(null==key){
return null;
}
return redisTemplate.opsForValue().get(key);
}
/**
* 很明显先get再set就说先获取key值对应的value然后再set 新的value 值。
* @Author: 妖妖玖
* @UpdateUser:
* @Version: 0.0.1
* @param key
• * @param value
* @return java.lang.Object
* @throws
*/
public Object getSet(String key,Object value){
if(null==key){
return null;
}
return redisTemplate.opsForValue().getAndSet(key,value);
}
/**
* 通过批量的key获取批量的value
* @Author: 妖妖玖
迎学教育
* @UpdateUser:
* @Version: 0.0.1
* @param keys
* @return java.util.List
* @throws
*/
public List