Springboot整合Redisson
基本配置参考这个博客:
https://blog.csdn.net/vistaed/article/details/107026758
本人使用的springboot版本是2.1.5
依赖如下:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.1</version>
<exclusions>
<exclusion>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-22</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<!-- for Spring Data Redis v.2.1.x -->
<artifactId>redisson-spring-data-21</artifactId>
<version>3.13.1</version>
</dependency>
- 需要注意的目前3.13.1所以依赖的 是redisson-spring-data-22,参考:https://github.com/redisson/redisson/tree/master/redisson-spring-boot-starter
- 说明如果是redisson-spring-data-22 的话对应的springboot版本就是2.2.x 的版本~~
所以要向上面那样,先排除掉redisson-spring-data-22 再单独加入
redisson-spring-data-21
之后,在resource下面加入redisson-single.yml配置文件
内容如下:可以参考官网:https://github.com/redisson/redisson/wiki/2.-Configuration#221-yaml-file-based-configuration
# 单节点配置 singleServerConfig: # 连接空闲超时,单位:毫秒 idleConnectionTimeout: 10000 # 连接超时,单位:毫秒 connectTimeout: 10000 # 命令等待超时,单位:毫秒 timeout: 3000 # 命令失败重试次数,如果尝试达到 retryAttempts(命令失败重试次数) 仍然不能将命令发送至某个指定的节点时,将抛出错误。 # 如果尝试在此限制之内发送成功,则开始启用 timeout(命令等待超时) 计时。 retryAttempts: 3 # 命令重试发送时间间隔,单位:毫秒 retryInterval: 1500 # # 重新连接时间间隔,单位:毫秒 # reconnectionTimeout: 3000 # # 执行失败最大次数 # failedAttempts: 3 # 密码 password: 1234 # 单个连接最大订阅数量 subscriptionsPerConnection: 5 # 客户端名称 clientName: null # # 节点地址 address: "redis://127.0.0.1:6379" # 发布和订阅连接的最小空闲连接数 subscriptionConnectionMinimumIdleSize: 1 # 发布和订阅连接池大小 subscriptionConnectionPoolSize: 50 # 最小空闲连接数 connectionMinimumIdleSize: 500 # 连接池大小 connectionPoolSize: 1000 # 数据库编号 database: 0 # DNS监测时间间隔,单位:毫秒 dnsMonitoringInterval: 5000 # 线程池数量,默认值: 当前处理核数量 * 2 threads: 16 # Netty线程池数量,默认值: 当前处理核数量 * 2 nettyThreads: 32 # 编码,不使用默认编码,因为set进去之后是乱码 #codec: !<org.redisson.codec.MarshallingCodec> {} # 传输模式 transportMode : "NIO"
配置Redisson参考了:https://blog.csdn.net/atu1111/article/details/106325258?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.highlightwordscore&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.highlightwordscore
import java.io.IOException; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.client.codec.Codec; import org.redisson.config.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @Configuration public class RedssonConfig { // 加载配置文件,装配RedissonClient @Bean(destroyMethod = "shutdown") public RedissonClient redisson() throws IOException { Config config = Config.fromYAML(new ClassPathResource("redisson-single.yml").getInputStream()); Codec codec=new FastJsonCodec(); config.setCodec(codec); RedissonClient redisson = Redisson.create(config); return redisson; } }
import java.io.IOException; import java.nio.charset.Charset; import org.redisson.client.codec.BaseCodec; import org.redisson.client.protocol.Decoder; import org.redisson.client.protocol.Encoder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; public class FastJsonCodec extends BaseCodec { // 开启对于AutoType的支持 // https://github.com/alibaba/fastjson/wiki/enable_autotype public static final ParserConfig defaultConfig = new ParserConfig(); static { defaultConfig.setAutoTypeSupport(true); } private final Encoder encoder = in -> { ByteBuf out = ByteBufAllocator.DEFAULT.buffer(); try { ByteBufOutputStream os = new ByteBufOutputStream(out); JSON.writeJSONString(os, in, SerializerFeature.WriteClassName); return os.buffer(); } catch (IOException e) { out.release(); throw e; } catch (Exception e) { out.release(); throw new IOException(e); } }; private final Decoder<Object> decoder = (buf, state) -> JSON.parseObject(new ByteBufInputStream(buf), Charset.forName("UTF-8"), Object.class, defaultConfig); //JSON.parseObject(new ByteBufInputStream(buf), Object.class); @Override public Decoder<Object> getValueDecoder() { return decoder; } @Override public Encoder getValueEncoder() { return encoder; } }
测试:可以直接把接口返回值改成LoginVo,参数都是String类型,电话号码和密码,不贴了
import java.util.concurrent.TimeUnit; import org.redisson.api.RBucket; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import cn.dk.su.common.result.Result; import cn.dk.su.common.rpc.user.vo.LoginVo; @Controller @RequestMapping("/redisson") public class TestRedisson { @Autowired private RedissonClient redissonClient; @RequestMapping(value = "/set", method = RequestMethod.GET) @ResponseBody public Result<LoginVo> set() { RBucket<LoginVo> bucket = redissonClient.getBucket("key"); LoginVo loginVo = new LoginVo(); loginVo.setPassword("222222"); loginVo.setTelephone("13000000000"); bucket.set(loginvo, 2, TimeUnit.MINUTES); return Result.success(bucket.get()); } // 下面这俩函数实际上没用到 public static <T> String beanToString(T value) { if (value == null) { return null; } Class<?> clazz = value.getClass(); if (clazz == int.class || clazz == Integer.class) { return "" + value; } else if (clazz == String.class) { return (String) value; } else if (clazz == long.class || clazz == Long.class) { return "" + value; } else { return JSON.toJSONString(value); } } // 获得value之后,将String转化为类对象 public static <T> T stringToBean(String str, Class<T> clazz) { if (str == null || str.length() <= 0 || clazz == null) { return null; } if (clazz == int.class || clazz == Integer.class) { return (T) Integer.valueOf(str); } else if (clazz == String.class) { return (T) str; } else if (clazz == long.class || clazz == Long.class) { return (T) Long.valueOf(str); } else { return JSON.toJavaObject(JSON.parseObject(str), clazz); } } }
结果: