SpringBoot集成Redis
springboot对redis进行了很好的自动化封装。
一.Redis简介
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
二.Redis安装
安装redis,并且找一个安装Redis Desktop Manager可视化工具,方便看存储的数据。
三.如何使用
1.引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
2.添加配置文件
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 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
3.添加cache 的配置类
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } }
使用了注解:@EnableCaching
来开启缓存。
4、好了,接下来就可以直接使用了
@Test public void test() throws Exception { stringRedisTemplate.opsForValue().set("aaa", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); } @Test public void testObj() throws Exception { User user=new User("[email protected]", "aa", "aa123456", "aa","123"); ValueOperations<String, User> operations=redisTemplate.opsForValue(); operations.set("com.xpcx", user); operations.set("com.xpc.f", user,1, TimeUnit.SECONDS); Thread.sleep(1000); //redisTemplate.delete("com.xpc.f"); boolean exists=redisTemplate.hasKey("com.xpcx"); User ruser = operations.get("com.xpcx"); System.out.println(ruser.toString()); if(exists){ System.out.println("exists is true"); }else{ System.out.println("exists is false"); } // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName()); }
5.测试结果
2019-03-30 14:44:05.642 INFO 7912 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing 2019-03-30 14:44:05.658 INFO 7912 --- [ main] com.xpc.TestRedis : Started TestRedis in 3.259 seconds (JVM running for 3.875) User{id=null, userName='aa', password='aa123456', email='[email protected]', nickname='aa', regTime='123'} exists is true
使用Redis Desktop Manager查看缓存
6.web中的使用
@RequestMapping("/getUser") @Cacheable(value="user-key") public User getUser() { User user=new User("[email protected]", "aa", "aa123456", "aa","123"); System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功"); return user; }
UserController层的代码
@Autowired UserController userController; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Test public void contextLoads() { System.out.println("hello web"); User user=new User("[email protected]", "aa", "aa123456", "aa","123"); ValueOperations<String, User> operations=redisTemplate.opsForValue(); operations.set("user-key", user); userController.getUser(); }
测试结果
2019-03-30 14:56:06.022 INFO 6412 --- [ main] com.xpc.RedisApplicationTests : Started RedisApplicationTests in 3.28 seconds (JVM running for 3.892) hello web 2019-03-30 14:56:06.187 INFO 6412 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
说明从缓存里面读的user。
这就是简单的springboot整合redis的过程。