SpringBoot连接redis集群
application.xml配置文件配置
(1)哨兵
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=127.0.0.1:26379
(2)去中心化
spring.redis.cluster.nodes=127.0.0.1:8001,127.0.0.1:8002,127.0.0.1:8003,127.0.0.1:8004,127.0.0.1:8005,127.0.0.1:8006
springboot使用场景
(1)作为缓存
1.为什么使用缓存?
减少数据库的访问频率。 提高数据的访问率。
2.什么样的数据适合放入缓存?
1.热点数据。 2. 修改频率比较低。3.安全系数低的。
缓存的原理:
程序首先去访问redis缓存,如果缓存中没有数据,就去访问数据库
而数据库会把操作的数据放入到redis缓存中
如何使用缓存
(1)搭建一个springboot+mp的工程
(2)引入redis相关的依赖
(3)配置redis
1. 配置application.properties文件
(4)service代码
#Redis服务器IP地址
spring.redis.host=192.168.31.33
#Redis服务器端口号
spring.redis.port=6379
#Redis服务器最大活跃数
spring.redis.jedis.pool.max-active=20
#Redis服务器最大空闲数
spring.redis.jedis.pool.max-idle=8
#Redis服务器最小空闲数
spring.redis.jedis.pool.min-idle=0
#Redis服务器链接最大超时20000
spring.redis.jedis.pool.max-wait=20000
# 哨兵模式开启下面的
# spring.redis.sentinel.master=mymaster
# spring.redis.sentinel.nodes=192.168.213.188:26379
# 去中心化集群
# spring.redis.cluster.nodes=192.168.213.188:8001,192.168.213.188:8002,192.168.213.188:8003,192.168.213.188:8004,192.168.213.188:8005,192.168.213.188:8006
. 创建RedisConfig文件
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;