SpringBoot整合Redis

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;
  }
  

 

 
posted @ 2023-09-05 23:48  jessi呀  阅读(137)  评论(0编辑  收藏  举报