首页 > 数据库 >SpringBoot整合Redis

SpringBoot整合Redis

时间:2023-09-05 23:56:22浏览次数:41  
标签:key redisson SpringBoot Redis redis springframework 整合 org config

SpringBoot整合Redis

整合spring cache

  1. 导入依赖

   <!-- 引入redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
​
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
​
        <!-- 以后使用Redisson作为所有分布式锁 -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.12.0</version>
        </dependency>
​
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
  1. 对文件进行配置application.yml

#    redis配置
  redis:
    host: 192.168.174.135
    port: 6379
    password: 123321
​
  cache:
    type: redis
    redis:
      time-to-live: 360000
      key-prefix: CACHE_
      use-key-prefix: true
      cache-null-values: true
  1. 加入配置类MyCacheConfig

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
​
/**
 * @author 李捷禧
 * Date: 2023/6/27
 * ClassName: MyCacheConfig
 */
​
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {
​
    // @Autowired
    // public CacheProperties cacheProperties;
​
    /**
     * 配置文件的配置没有用上
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
​
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // config = config.entryTtl();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
​
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //将配置文件中所有的配置都生效
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
​
        return config;
    }
​
}
  1. 在service层对需要加缓存的类加入缓存注解

//注入redis中的缓存
@Cacheable(value = "category",key = "#root.methodName")
//删除redis中的缓存
 @CacheEvict(value = "category",allEntries = true)
 还有更多

整合StringRedisTemplate

加入依赖,配置

在service层实现

//判断能否的出值,如果是空值就进行数据库查询
String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
//进行数据库查询设置
        stringRedisTemplate.opsForValue().set("catalogJson", valueJson, 1, TimeUnit.DAYS);
//设置的时候,要注意后面的参数,逻辑过期时间(1是参数大小,TimeUnit.DAYS是单位)

理解redisson分布式锁

配置Redisson

导入依赖

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.12.0</version>
</dependency>
MyRedissonConfig
@Configuration
public class MyRedissonConfig {
​
    /**
     * 所有对Redisson的使用都是通过RedissonClient
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod="shutdown")
    public RedissonClient redisson() throws IOException {
        //1、创建配置
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.174.135:6379").setPassword("123321");
​
        //2、根据Config创建出RedissonClient实例
        //Redis url should start with redis:// or rediss://
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
​
}

什么是分布式锁?

分布式锁是一种同步机制,用于确保同一时间只有一个进程可以访问共享资源。在分布式系统中,多个进程可能需要同时访问共享资源,这时分布式锁的作用就显得尤为重要。

Redis 分布式锁

Redis 是一个高性能的键值存储系统,支持原子操作和高并发访问。由于这些特性,Redis 被广泛用作分布式锁的实现

实例1:

public class DistributedRedisLock {
  //从配置类中获取redisson对象
  private static Redisson redisson = RedissonManager.getRedisson();
  private static final String LOCK_TITLE = "redisLock_";
  
  //加锁
  public static boolean acquire(String lockName){
    //声明key对象
    String key = LOCK_TITLE + lockName;
    //获取锁对象
    
    RLock mylock = redisson.getLock(key);
    //加锁,并且设置锁过期时间3秒,防止死锁的产生  uuid+threadId
      
     // 记得设置锁的过期时间
    mylock.lock(2,3,TimeUtil.SECOND);
    //加锁成功
    return  true;
  }
  
  //锁的释放
  public static void release(String lockName){
    //必须是和加锁时的同一个key
    String key = LOCK_TITLE + lockName;
    //获取所对象
    RLock mylock = redisson.getLock(key);
    //释放锁(解锁)
    mylock.unlock();
  }

实例2:

public class DistributedRedisLock2 {
  //从配置类中获取redisson对象
  private static Redisson redisson = RedissonManager.getRedisson();
  private static final String LOCK_TITLE = "redisLock_";
  
  //加锁
  public static boolean acquire(String lockName){
    //声明key对象
    String key = LOCK_TITLE + lockName;
    //获取锁对象
    
    RLock mylock = redisson.getLock(key);
    //加锁,并且设置锁过期时间3秒,防止死锁的产生  uuid+threadId
    try{
      boolean isLock =  mylock.tryLock(1,300,TimeUtil.SECOND);
        if(isLock){
            stringRedisTemplate.opsForValue()
                .set("catalogJson", valueJson, 1, TimeUnit.DAYS);
        }
    }catch{
        //抛出异常
         throw new e
    }finally{
        mylock.unlock();
    }
     // 记得设置锁的过期时间
    //mylock.lock(2,3,TimeUtil.SECOND);
    //加锁成功
    return  true;
  }
  

 

 

标签:key,redisson,SpringBoot,Redis,redis,springframework,整合,org,config
From: https://www.cnblogs.com/jessi200/p/17681214.html

相关文章

  • 007-SpringBoot+Mybatis+Sqlite框架搭建
    1,配置文件(application.yaml)server:port:6695spring:datasource:url:jdbc:sqlite:D:/examtolearn.dbusername:password:driver-class-name:org.sqlite.JDBCmybatis:mapper-locations:classpath:mapper/*.xmlconfiguration:log-......
  • 使用 Docker Compose 部署 Redis Sentinel 高可用架构
    在现代应用中,无法容忍系统中断或数据丢失。Redis作为一种高性能的内存数据库,被广泛应用于缓存、会话管理等场景。然而,即使我们拥有可伸缩的RedisCluster集群,也需要考虑在主节点故障时自动切换到从节点的机制。这时候RedisSentinel就派上用场了。高可用性是分布式应用的核心......
  • redis cluster集群安装(CentOS7 + redis 5.0.14)
    Linux系统-部署-运维系列导航 rediscluster介绍redis最开始使用主从模式做集群,若master宕机需要手动配置slave转为master;后来为了高可用提出来哨兵模式,该模式下有一个哨兵监视master和slave,若master宕机可自动将slave转为master,但它也有一个问题,就是不能动态扩充;所以在3.x提......
  • redis分布式锁幂等性问题
    一.与Transcational注解同时使用如果是自定义的切面,切面类要加@Order(Ordered.HIGHEST_PRECEDENCE),保证redis锁的切面在事务切面外面,让事务先提交,再释放redis锁。二.日期字段是datetime背景:jmeter 500并发测试接口出现重复插入。接口逻辑如下 服务器查看日志如下数据......
  • Springboot+Quartz+Dynamic-datasource
    在使用dynamic-datasource多数据源切换场景下,实现Quartz任务持久化配置和API动态调度1.pom依赖暂未找到版本对应关系,若有版本不一致异常,请自行尝试升降版本。<dependencies><!--动态数据源--><dependency><groupId>com.baomidou</groupI......
  • Redis 单线程快的原因
    Redis单线程快的原因为什么Redis单线程却能高并发纯内存操作核心是基于非阻塞的IO多路复用机制单线程反而避免了多线程的频繁上下文切换问题Redis的高并发快的原因Redis是基于内存的,内存的读写速度非常快;数据存在内存中,数据结构用HashMap,HashMap的优势就是查找和操......
  • springboot加载bean失败:No matching autowired candidates found
    场景:之前在培训轮岗,一直没有干活,最近开始干活遇到xxljob,打算自己学习了解一下。在按照文档配置执行器项目时,发现怎么启动,xxlJobExecutor都没有被加载进来。解决:后来经过查阅,原来是springBoot启动默认扫描的是启动类所在的包以及其子包,而我的文件为:因此bean注入失败。把......
  • Redis数据结构
    5种基础数据结构:String(字符串)、List(列表)、Set(集合)、Hash(散列)、Zset(有序集合)。这5种数据结构是直接提供给用户使用的,是数据的保存形式,其底层实现主要依赖这8种数据结构:简单动态字符串(SDS)、LinkedList(双向链表)、HashTable(哈希表)、SkipList(跳跃表)、Intset(整数集合)、ZipLis......
  • Docker 部署 Jenkins 构建 SpringBoot 工程发布镜像
    说明全部都基于Docker服务搭建使用,首先用Docker安装Jenkins环境,Docker安装GitLab版本管理系统,执行Jenkins拉取指定版本tag进行编译构建,在用SonarQube进行代码质量检测,在打包制作镜像,发布到Harbor镜像仓库,最后启动SpringBoot工程并进行访问。系统平台CentOSLinu......
  • springboot启动错误: 找不到或无法加载主类
    当在eclipse启动springboot项目时出现问题:springboot错误:找不到或无法加载主类解决办法:1,通过cmd命令行,进入项目目录进行,mvncleaninstall进行编译项目install后,再到eclipse上选中项目按F5刷新项目。再运行即可问题解决。2,在eclipse上选中项目 点击clean清理项目再运行问......