SpringBoot 整合 Redis

归纳总结 SpringBoot 整合 Redis,进行数据操作。

引入 maven 依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

数据源相关配置

1
2
3
4
5
6
7
8
9
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0

数据访问层,使用 redisTemplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Repository
public class RedisBaseDao {

@Resource(name="redisTemplate")
protected ValueOperations<String, String> valueOperations;

public void addValue(String key, String value){
valueOperations.set(key, value);
}

public String getValue(String key){
return valueOperations.get(key);
}
}

单元测试用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {

public static Logger logger= LoggerFactory.getLogger(SpringbootRedisApplicationTests.class);
@Test
public void contextLoads() {
}

@Autowired
RedisDao redisDao;
@Test
public void testRedis(){
redisDao.setKey("key","hello");
logger.info(redisDao.getValue("key"));
}
}
-------------本文结束感谢您的阅读-------------
Thank you for your encouragement