簡介
Redis 是目前使用十分普遍的內存數據庫。Redis 比 Memcached 支持更豐富的數據類型,如 Lists, Hashes, Sets 及 Ordered Sets 等,支持數據持久化、備份;除此以外,Redis 還支持事務,HA,主從庫,同時兼具了非關係型數據庫與關係型數據的特性,有着豐富的應用場景。node
使用
一、引入依賴redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.0</version> </dependency>
二、配置
單機模式spring
# 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.jedis.pool.max-active=8 # 鏈接池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.jedis.pool.max-wait=-1 # 鏈接池中的最大空閒鏈接 spring.redis.jedis.pool.max-idle=8 # 鏈接池中的最小空閒鏈接 spring.redis.jedis.pool.min-idle=0 # 鏈接超時時間(毫秒) spring.redis.timeout=5000
哨兵模式數據庫
spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 spring.redis.timeout=5000 spring.redis.database=0 spring.redis.sentinel.master=mymaster spring.redis.sentinel.nodes=127.0.0.1:26380,127.0.0.1:26381,127.0.0.1:26382 spring.redis.password=
三、測試apache
@RunWith(SpringRunner.class) @SpringBootTest public class RedisTests { @Autowired private StringRedisTemplate stringRedisTemplate; @Test public void contextLoads() { } @Test public void setRedis(){ stringRedisTemplate.opsForValue().set("key1","張三"); } @Test public void getRedis(){ String s = stringRedisTemplate.opsForValue().get("key1"); System.out.println("s: "+s); } }
四、實現共享Session
引入依賴服務器
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
配置session
@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400) public class SessionConfig { }
maxInactiveIntervalInSeconds: 設置 Session 失效時間
使用 Redis Session 以後,原 Spring Boot 的 server.session.timeout 屬性再也不生效。spring-boot
END測試