Windows:
下载地址:Redis
Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载Redis-x64-xxx.zip压缩包到 C 盘,解压后,将文件夹重新命名为 Redis。
1.pom.xml
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.application
# Redis Setting
# 服务器IP
spring.redis.host=192.168.0.134
# 端口号
spring.redis.port=6379
# 数据库索引,默认为0
spring.redis.database=0
# 连接密码,默认为空
spring.redis.password=
# Redis连接池配置
# 连接池最大连接数,使用负值表示没有限制
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间,使用负值表示没有限制
spring.redis.lettuce.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
# 空闲链接检测线程检测周期;如果为负值,表示不运行检测线程;单位毫秒,默认为-1
spring.redis.lettuce.pool.time-between-eviction-runs=60000
# 关闭超时时间
spring.redis.lettuce.shutdown-timeout=3000ms
3.RedisUtil
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
/**
* Redis最为常用的数据类型主要有以下:String\Hash\List\Set
* 作者:我是沐沫
* 时间:2019.05.16
*/
@Service
public class RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 读取缓存
*/
public String select(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 写入缓存
* 天:DAYS 小时:HOURS 分:MINUTES 秒:SECONDS 毫秒:MILLISECONDS
*/
public boolean insert(String key, String value ,long time) {
boolean result = false;
try {
stringRedisTemplate.opsForValue().set(key,value,time,TimeUnit.MINUTES);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 更新缓存
*/
public boolean update(String key, String value) {
boolean result = false;
try {
stringRedisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 删除缓存
*/
public boolean delete(final String key) {
boolean result = false;
try {
stringRedisTemplate.delete(key);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
4.TestController
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisUtil redisUtil;
@RequestMapping("/redis")
public String redis() {
// 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
String string = stringRedisTemplate.opsForValue().get("aaa");
System.out.println(string);
redisUtil.insert("aaa", "111");
System.out.println(redisUtil.select("aaa"));
return "Redis";
}