我们都知道将首页数据放在Redis中可以加快首页数据的访问速度。但是如何才能准确快速地将Redis集成到我们的SpringBoot2.x项目中呢?今天,阿芬就带大家走一遍门道。Redis简介Redis使用的是文本协议,比较浪费流量,但是由于它的数据是存储在内存中的,所以相对来说还是可以达到极高的访问性能。而且Redis是线程安全的。RESP是Redis序列化协议的缩写。它是一种直观的文本协议,具有实现极其简单的优点,并且具有出色的解析性能。虽然Redis协议中存在大量冗余的回车和换行,但这并不影响它成为技术领域非常流行的文本协议。在技??术领域,性能并不总是一切,简单性、可理解性和易于实施都需要适当平衡。Redis基本数据结构1、String:(缓存)key:valuevalue可以是对象转换成的JSON字符串,也可以是对象序列化后的二进制字符串2、List:(异步队列)类似于链表,右入左出:队列rightinandrightout:stack3.Dictionary(hash)类似于hashmap:array+linkedlist但rehash是一种渐进的hash策略4.Collection:(去重)Unorderedset:类似于hashsetOrderedzset:类似于SortedSet和HashMap内部实现是一个跳转列表Lettuce。随着SpringBoot2.x的到来,支持的组件也越来越丰富和成熟。其中,对Redis的支持不仅丰富了它的API,还替换掉底层的Jedis依赖,换成Lettuce。虽然Lettuce和Jedis都是连接RedisServer的客户端程序,但是Jedis在实现上是直接连接RedisServer的,在多线程环境下不是线程安全的,除非使用连接池为每个Jedis添加物理连接实例。Lettuce基于Netty的连接实例(StatefulRedisConnection),可以在多线程间并发访问,线程安全,满足多线程环境下的并发访问。同时,它是一个可扩展的设计。如果一个连接实例不够用,也可以按需要添加的连接实例。Lettuce是一个可扩展的Redis客户端,用于构建非阻塞的Reactive应用程序。Luttuce官网:https://lettuce.io/Google翻译后的页面是:原来这个东西叫lettuce,不说了,看图标确实有点像。实际项目中使用的SpringBoot2.x实现,如果之前是SpringBoot1.x,需要注意,底层已经从Jedis升级到了Lettuce。3.1.引入依赖除了SpringBoot项目需要的jar包外,还需要引入redis相关的依赖:org.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool23.2、这里使用application.yml配置文件。yml文件,配置如下:spring:redis:#Redis默认有16个分片,具体分片在这里配置。默认为索引为0的分片数据库:1#Redis服务器地址host:127.0.0.1#Redis服务器连接端口port:6379#Redis服务器连接密码(默认为空)password:mmzsblog#连接超时时间(毫秒)timeout:2000s#在配置文件中添加lettuce.pool相关配置,会使用lettuce连接池lettuce:pool:#连接池的最大阻塞等待时间(使用负值表示不限制)默认-1max-wait:60s#连接池中最大空闲连接数默认为8max-idle:10#连接池中最小空闲连接数默认为0min-idle:10#连接池中最大连接数(使用负值表示无限制)默认为8max-activ:8如果项目是SpringBoot1.x升级到SpringBoot2.x时,会使用jedis连接池配置来配置jedis相关属性:#将jedis.pool相关配置添加到配置onfile,jedis连接池会使用jedis:pool:max-active:10max-idle:8min-idle:0max-wait:60s引用的jar包也需要调整:org.springframework.bootspring-boot-starter-data-redisio.lettucelettuce-coreredis.clientsjedis另外这里有一篇关于SpringBoot的帖子RedisProperties的所有配置项#REDISRedisPropertiesspring.redis.cluster.max-redirects=#Maximumnumberofredirectstofollowwhenexecutingcommandsacrossthecluster.spring.redis.cluster.nodes=#Comma-separatedlistof"host:port"pairstobootstrapfrom.spring.redis.database=0#Databaseindexusedbytheconnectionfactory.spring.redis.url=#ConnectionURL.Overrideshost,port,andpassword.Userisignored.Example:redis://user:password@example.com:6379spring.redis.host=localhost#Redisserverhost.spring.redis.jedis.pool.max-active=8#Maximumnumberofconnectionsthatcanbeallocatedbythepoolatagiventime.Useanegativevaluefornolimit.spring.redis.jedis.pool.max-idle=8#Maximumnumberof"idle"connectionsinthepool.Useanegativevaluetoindicateanunlimitednumberofidleconnections.spring.redis.jedis.pool.max-wait=-1ms#Maximumamountoftimeaconnectionallocationshouldblockbeforethrowinganexceptionwhenthepoolisexhausted.Useanegativevaluetoblockindefinitely.spring.redis.jedis.pool.min-idle=0#Targetfortheminimumnumberofidleconnectionstomaintaininthepool.Thissettingonlyhasaneffectifitispositive.spring.redis.lettuce.pool.max-active=8#Maximumnumberofconnectionsthatcanbeallocatedbythepoolatagiventime.Useannegativevaluefornolimit.spring.redis.lettuce.pool.max-idle=8#Maximumnumberof"空闲"连接在池中。.pool.max-wait=-1ms#Maximumamountoftimeaconnectionallocationshouldblockbeforethrowinganexceptionwhenthepoolisexhausted.Useanegativevaluetoblockindefinitely.spring.redis.lettuce.pool.min-idle=0#Targetfortheminimumnumberofidleconnectionstomaintaininthepool.Thissettingonlyhasaneffectifitispositive.spring.redis.lettuce.shutdown-timeout..shutdowntimeout.shutdowntimeout=100ms#Shutdowntimeout.targetfortheminimumnumberofidleconnections保持在池中。password=#Loginpasswordoftheredisserver.spring.redis.port=6379#Redisserverport.spring.redis.sentinel.master=#NameoftheRedisserver.spring.redis.sentinel.nodes=#Comma-separatedlistof"host:port"pairs.spring.redis.ssl=false#WhethertoenableSSLsupport.spring.redis.timeout=#Connectiontimeout.3.3,自定义一个RedisTemplate这个看你的,不自定义就不行影响使用,只说可能没那么容易,所以阿芬习惯自定义一个,因为SpringBoot在RedisAutoConfiguration中默认配置了两个模板类,RedisTemplate和StringRedisTemplate,但是RedisTemplate没有指定key和value序列化器。@ConfigurationpublicclassRestTemplateConfig{@BeanpublicRedisTemplateredisCacheTemplate(LettuceConnectionFactoryredisConnectionFactory){RedisTemplatetemplate=newRedisTemplate<>();template.setKeySerializer(newStringRedisSerializer());template.setValueSerializer(newGenericJackory2JsonRedisSerializerConnection());F(redisConnectionFactory);返回模板;}}3.4。Person实体类声明一个Person实体类:/***@author:createdbymmzsblog*@date:createdat2020/06/2316:41*/@Data@NoArgsConstructor@AllArgsConstructorpublicclassPersonimplementsSerializable{privatestaticfinallongserial-UrsionID=8183942491930372236L;privateLonguserId;privateStringusername;3.5.通过编写UserController进行测试:@RestControllerpublicclassUserController{@ResourceprivateRedisTemplateredisTemplate;@ResourceprivateStringRedisTemplatestringRedisTemplate;@GetMapping("/set")publicStringRedset{sTemplate.opsForValue().set("one","1");//redisTemplate保存的是字节序列,因为在自定义RestTemplateConfig的时候指定了key和value的serializerredisTemplate.opsForValue().set("two","2");redisTemplate.opsForValue().set("person",newPerson(1L,"luffy","123456789"));//测试线安全ExecutorServiceexecutorService=Executors.newFixedThreadPool(1000);IntStream.range(0,1000).forEach(i->{executorService.execute(()->stringRedisTemplate.opsForValue().increment("num",1));});返回"好的!";}@GetMapping("/get")publicStringget(){Stringone=stringRedisTemplate.opsForValue().get("one");if("1".equals(one)){System.out.println("key:one"+"||value:"+one);}Objecttwo=redisTemplate.opsForValue().get("two");if("2".equals(two.toString())){System.out.println("key:two"+"||value:"+two);}Personuser=(Person)redisTemplate.opsForValue().get("person");if("路飞".equals(user.getUsername())){System.out.println("key:person"+"||value:"+user);}return"Ok!";}}使用RedisDesktopManager工具查看数据如下:StringRedisTemplate设置的key值为String类型:RedisTemplate设置的key值以二进制字节流的形式存储,从screenshot也可以看到[Binary]标识符:自定义的RedisTemplate和StringRedisTemplate没有冲突。使用String存储还是二进制字节流存储完全取决于你。参考https://lettuce.io/SpringBoot官方文档91.4《Redis深度历险:核心原理和应用实践》http://blog.battcn.com/2018/05/11/springboot/v2-nosql-redis/https://www.jianshu。com/p/f7d11e7109b7