一、步驟:
1、下載並安裝Redis
windows 下載安裝
Redis下載鏈接:https://github.com/MicrosoftArchive/redis/releases
簡單直接.msi 一鍵安裝版
或者下載Zip壓縮包
Linux 下載安裝 使用yum安裝
更改yum源
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
下載新的CentOS-Base.repo 到/etc/yum.repos.d/
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
安裝
yum install redis
啓動
systemctl start redis.service
設置開機自啓
systemctl enable redis.service
密碼:
打開文件/etc/redis.conf,找到其中的# requirepass foobared,去掉前面的#,並把foobared改成你的密碼。
2、項目pom文件加入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3、application.properties中加入redis相關配置
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=192.168.0.24
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認爲空)
spring.redis.password= 你的密碼
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=200
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閒連接
spring.redis.pool.max-idle=10
# 連接池中的最小空閒連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=1000
4、配置類
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
/** * Logger */
private static final Logger lg = LoggerFactory.getLogger(RedisConfig.class);
@Bean
public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
5、注入實例
@Autowired private StringRedisTemplate stringRedisTemplate;
測試
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testRedis() {
stringRedisTemplate.opsForValue().set("姓名","小明");
String str = stringRedisTemplate.opsForValue().get("姓名");
System.out.println(str);
return str;
}
如果報connect 超時 Linux 關閉防火牆 或者 修改Redis配置文件 註釋 bind 127.0.0.1 即解綁本機IP 並開啓遠程訪問權限