Spring Boot基礎教程17-使用NoSQL數據庫-redis

redis windows 版本下載: https://github.com/MSOpenTech/redis/releases 
一、 添加依賴 
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、 配置文件: 
#redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456
#spring.redis.database=0
#spring.redis.pool.max-active=8 
#spring.redis.pool.max-idle=8 
#spring.redis.pool.max-wait=-1 
#spring.redis.pool.min-idle=0 
#spring.redis.timeout=0
三、 測試 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
* @author wujing
*/
@Component
public class RoncooRedisComponent {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void set(String key, String value) {
ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
if (!this.stringRedisTemplate.hasKey(key)) {
ops.set(key, value);
System.out.println("set key success");

} else {
// 存在則打印之前的 value 值
System.out.println("this key = " + ops.get(key));
}
}
public String get(String key) {
return this.stringRedisTemplate.opsForValue().get(key);
}
public void del(String key) {
this.stringRedisTemplate.delete(key);
}
}
@Autowired
private RoncooRedisComponent roncooRedisComponent;
@Test
public void set() {
roncooRedisComponent.set("roncoo", "hello world");
}
@Test
public void get() {
System.out.println(roncooRedisComponent.get("roncoo"));
}
@Test
public void del() {
roncooRedisComponent.del("roncoo");

注:生產環境下,如果外網可以訪問,一定要設置密碼!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章