一.maven中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二.application.properties中添加配置:
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000
三.RedisTemplate的使用:
package demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* description:
* author:
* date: 2018-12-13 17:13
**/
public class RedisUtil {
@Autowired
RedisTemplate redisTemplate;
/**
* string类型设值
* @param str
* @param obj
* @return
*/
public boolean set(String str,Object obj){
try {
redisTemplate.opsForValue().set(str,obj);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* string类型获取值
* @param str
* @return
*/
public Object get(String str){
try {
Object o = redisTemplate.opsForValue().get(str);
return o;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* string类型批新增
* @param map
* @return
*/
public boolean mset(Map<String, Object> map){
try {
redisTemplate.opsForValue().multiSet(map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* string类型批获取
* @param list
* @return
*/
public List mget(List<String> list){
try {
List list1 = redisTemplate.opsForValue().multiGet(list);
return list1;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* string类型获取所有
* @return
*/
public List mgetAll(){
try {
Set keys = redisTemplate.keys("*");
List list = redisTemplate.opsForValue().multiGet(keys);
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* hash类型批新增
* @param map
* @return
*/
public boolean hmset(Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll("hashKey",map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* hash类型获取
* @param str
* @return
*/
public Object hget(String str){
try {
Object obj = redisTemplate.opsForHash().get("hashKey", str);
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* hash类型获取所有value
* @return
*/
public Object hgetAllValue(){
try {
Object obj = redisTemplate.opsForHash().values("hashKey");
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* hash类型获取所有键值对
*
* @return
*/
public Map hgetAll() {
try {
Map entries = redisTemplate.opsForHash().entries("hashKey");
return entries;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* hash类型删除键值对
*
* @param keyArray 键的数组
* @return
*/
public boolean hdelete(String[] keyArray) {
Long delete = redisTemplate.opsForHash().delete("hashKey", keyArray);
System.out.println("删除的key、value键值对数量 = " + delete);
return true;
}
}