Spring Boot 整合之Redis
阿新 • • 發佈:2018-11-16
在新增 redis 依賴包啟動專案後,Spring Boot 會自動配置 RedisCacheManger 和 RedisTemplate 的 Bean。如果開發者不想使用 Spring Boot 寫好的 Redis 快取,而是想使用其 API 自己實現快取功能、訊息佇列或分散式鎖之類的需求時,可以繼續往下瀏覽。
Spring Data Redis 為我們提供 RedisTemplate 和 StringRedisTemplate 兩個模板進行資料操作,它們主要 的訪問方法如下:
方法 | 說明 |
---|---|
opsForValue() | 操作簡單屬性的資料 |
opsForList() | 操作含有 list 的資料 |
opsForSet() | 操作含有 set 的資料 |
opsForZSet() | 操作含有 zset 的資料 |
opsForHash() | 操作含有 hash 的資料 |
1.匯入依賴
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.配置連線屬性
# redis 配置
spring.redis.host=47.106.8.233
spring.redis.port=6379
spring.redis.password=redis123
# 快取過期時間,單位毫秒
spring.cache.redis.time-to-live=60000s
3.建立RedisDao
@Component public class RedisDao { @Autowired private StringRedisTemplate stringRedisTemplate; public void set(String key, String value) { this.stringRedisTemplate.opsForValue().set(key, value); } public String get(String key) { return this.stringRedisTemplate.opsForValue().get(key); } public void delete(String key) { this.stringRedisTemplate.delete(key); } }
4.測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDaoTest {
@Autowired
private RedisDao redisDao;
@Test
public void testSet() {
String key = "name";
String value = "zhangsan";
this.redisDao.set(key, value);
}
@Test
public void testGet() {
String key = "name";
String value = this.redisDao.get(key);
System.out.println(value);
}
@Test
public void testDelete() {
String key = "name";
this.redisDao.delete(key);
}
}