SpringBoot
是为了简化Spring
应用的建立、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让咱们能够更好的关注业务自己而不是外部的XML配置,咱们只需遵循规范,引入相关的依赖就能够轻易的搭建出一个 WEB 工程
Spring Boot
除了支持常见的ORM框架外,更是对经常使用的中间件提供了很是好封装,随着Spring Boot2.x
的到来,支持的组件愈来愈丰富,也愈来愈成熟,其中对Redis
的支持不单单是丰富了它的API,更是替换掉底层Jedis
的依赖,取而代之换成了Lettuce(生菜)
html
<!-- more -->java
Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。相比Memcached
它支持存储的类型相对更多(字符
、哈希
、集合
、有序集合
、列表
、GEO
),同时Redis
是线程安全的。2010年3月15日起,Redis的开发工做由VMware主持,2013年5月开始,Redis的开发由Pivotal
赞助。git
Lettuce
和 Jedis
的都是链接Redis Server
的客户端程序。Jedis
在实现上是直连redis server
,多线程环境下非线程安全,除非使用链接池,为每一个Jedis实例增长物理链接。Lettuce
基于Netty的链接实例(StatefulRedisConnection),能够在多个线程间并发访问,且线程安全,知足多线程环境下的并发访问,同时它是可伸缩的设计,一个链接实例不够的状况也能够按需增长链接实例。github
在 pom.xml
中spring-boot-starter-data-redis
的依赖,Spring Boot2.x
后底层不在是Jedis
若是作版本升级的朋友须要注意下web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
在 application.properties
文件中配置以下内容,因为Spring Boot2.x
的改动,链接池相关配置须要经过spring.redis.lettuce.pool
或者 spring.redis.jedis.pool
进行配置了redis
spring.redis.host=localhost spring.redis.password=battcn # 链接超时时间(毫秒) spring.redis.timeout=10000 # Redis默认状况下有16个分片,这里配置具体使用的分片,默认是0 spring.redis.database=0 # 链接池最大链接数(使用负值表示没有限制) 默认 8 spring.redis.lettuce.pool.max-active=8 # 链接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 spring.redis.lettuce.pool.max-wait=-1 # 链接池中的最大空闲链接 默认 8 spring.redis.lettuce.pool.max-idle=8 # 链接池中的最小空闲链接 默认 0 spring.redis.lettuce.pool.min-idle=0
Spring Boot
对Redis
的支持已经很是完善了,良好的序列化以及丰富的API足够应对平常开发spring
建立一个User
类数据库
package com.battcn.entity; import java.io.Serializable; /** * @author Levin * @since 2018/5/10 0007 */ public class User implements Serializable { private static final long serialVersionUID = 8655851615465363473L; private Long id; private String username; private String password; // TODO 省略get set }
默认状况下的模板只能支持RedisTemplate<String, String>
,也就是只能存入字符串,这在开发中是不友好的,因此自定义模板是颇有必要的,当自定义了模板又想使用String
存储这时候就可使用StringRedisTemplate
的方式,它们并不冲突...apache
package com.battcn.config; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.io.Serializable; /** * TODO 修改database * * @author Levin * @since 2018/5/10 0022 */ @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisCacheAutoConfiguration { @Bean public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Serializable> template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } }
完成准备事项后,编写一个junit
测试类来检验代码的正确性,有不少人质疑过Redis
线程安全性,故下面也提供了响应的测试案例,若有疑问欢迎指正缓存
package com.battcn; import com.battcn.entity.User; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import java.io.Serializable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.IntStream; /** * @author Levin * @since 2018/5/10 0010 */ @RunWith(SpringRunner.class) @SpringBootTest public class Chapter8ApplicationTest { private static final Logger log = LoggerFactory.getLogger(Chapter8ApplicationTest.class); @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<String, Serializable> redisCacheTemplate; @Test public void get() { // TODO 测试线程安全 ExecutorService executorService = Executors.newFixedThreadPool(1000); IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> stringRedisTemplate.opsForValue().increment("kk", 1)) ); stringRedisTemplate.opsForValue().set("k1", "v1"); final String k1 = stringRedisTemplate.opsForValue().get("k1"); log.info("[字符缓存结果] - [{}]", k1); // TODO 如下只演示整合,具体Redis命令能够参考官方文档,Spring Data Redis 只是改了个名字而已,Redis支持的命令它都支持 String key = "battcn:user:1"; redisCacheTemplate.opsForValue().set(key, new User(1L, "u1", "pa")); // TODO 对应 String(字符串) final User user = (User) redisCacheTemplate.opsForValue().get(key); log.info("[对象缓存结果] - [{}]", user); } }
其它类型
下列的就是Redis
其它类型所对应的操做方式
spring-data-redis
文档: https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/#new-in-2.0.0Redis
文档: https://redis.io/documentationRedis
中文文档: http://www.redis.cn/commands.html
目前不少大佬都写过关于 SpringBoot
的教程了,若有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE
编写,包括新版本的特性都会一块儿介绍...
battcn
全文代码:https://github.com/battcn/spring-boot2-learning/tree/master/chapter8