SpringBoot连接redis集群以及分布式锁

本文介绍了SpringBoot如何连接redis集群,并探讨了SpringBoot的使用场景,特别是作为缓存的角色。详细阐述了缓存的目的和适用数据类型,以及缓存的工作原理。接着深入讨论了分布式锁的概念,对比了线程锁、进程锁和分布式锁的差异,并指出了分布式锁在解决多进程并发问题中的应用。最后,提到了使用redis作为分布式锁的解决方案,推荐了redisson这一第三方组件。
摘要由CSDN通过智能技术生成

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;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值