Spring Boot 实践2 --项目中使用 Redis
Posted Coder_fang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 实践2 --项目中使用 Redis相关的知识,希望对你有一定的参考价值。
背景:基于实践1中,我们使用Redis做为缓存。
(转载请注明来源:cnblogs coder-fang)
- POM中加入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
- 在application.properties中加入配置:
spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.pool.max-idle=8 spring.redis.pool.max-active=8
- 创建RedisConfig类,并注入RedisTemplate bean:
package com.test.demo.config; 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.core.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory); return stringRedisTemplate; } }
- 实现redisRepostory通用功能:
package com.test.demo.db.repo.nosql; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; @Repository public class RedisRepository { @Autowired RedisTemplate<String, String> redisTemplate; public void add(String key,String value) { redisTemplate.opsForValue().set(key, value); } public void add(String key,String value,Long time) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.MINUTES); } public String get(String key) { return redisTemplate.opsForValue().get(key); } public void delete(String key) { redisTemplate.opsForValue().getOperations().delete(key); } }
- 创建单元测试并运行:
package com.test.demo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.test.demo.db.repo.nosql.RedisRepository; @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired RedisRepository redisRepo; @Test public void testRedis(){ redisRepo.add("test", "123", 1L); String val = redisRepo.get("test"); assertEquals(val, "123"); System.out.println(val); val = redisRepo.get("321"); System.out.println(val); assertNull(val); } }
YES,项目中使用redis已完成。
以上是关于Spring Boot 实践2 --项目中使用 Redis的主要内容,如果未能解决你的问题,请参考以下文章
(转)Spring Boot 2 :Docker Compose + Spring Boot + Nginx + Mysql 实践
spring-boot-starter-quartz集群实践
Spring Boot 2.x 实践记:Retry(annotion)