SpringBoot 2.X 整合redisson 创建分布式锁

引入Maven依赖

 <!-- https://mvnrepository.com/artifact/org.redisson/redisson -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.13.2</version>
        </dependency>

增加application.yaml配置

spring:
    redis:
      database: 1
      host: localhost
      port: 6709
      password:*****

增加redis配置文件

 import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @program: devicedataporocessor
 * @description: redis设置
 * @author: linwl
 * @create: 2020-07-01 11:05
 */
@Configuration
@Slf4j
public class RedisConfig {

  @Value("${spring.redis.host}")
  private String host;

  @Value("${spring.redis.port}")
  private String port;

  @Value("${spring.redis.password}")
  private String password;

  @Value("${spring.redis.database}")
  private int database;

  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(connectionFactory);

    // 使用Jackson2JsonRedisSerialize替换默认序列化
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
        new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    //    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

    // 设置key和value的序列化规则
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    // value hashmap序列化
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    // key haspmap序列化
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.afterPropertiesSet();

    return redisTemplate;
  }

  @Bean
  public RedissonClient getRedisson() {
    Config config = new Config();
    String url = "redis://" + host + ":" + port;
    config.useSingleServer().setAddress(url).setPassword(password).setDatabase(database);
    // 添加主从配置
    //
    // config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new
    // String[]{"",""});
    return Redisson.create(config);
  }
}

创建DistributedRedisLock类来方便使用分布式锁

 mport lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: devicedataporocessor
 * @description: 分布式锁工具类
 * @author: linwl
 * @create: 2020-07-16 16:55
 */
@Slf4j
@Component
public class DistributedRedisLock {

  @Autowired private RedissonClient redissonClient;

  /**
   * 获取分布式锁
   *
   * @param lockName
   * @return
   */
  public Boolean lock(String lockName) {
    try {
      if (redissonClient == null) {
        log.info("DistributedRedisLock redissonClient is null");
        return false;
      }

      RLock lock = redissonClient.getLock(lockName);
      // 锁10秒后自动释放,防止死锁
      lock.lock(10, TimeUnit.SECONDS);

      log.info(
          "Thread [{}] DistributedRedisLock lock [{}] success",
          Thread.currentThread().getName(),
          lockName);
      // 加锁成功
      return true;
    } catch (Exception e) {
      log.error("DistributedRedisLock lock [{}] Exception:", lockName, e);
      return false;
    }
  }

  /**
   * 释放分布式锁
   *
   * @param lockName
   * @return
   */
  public Boolean unlock(String lockName) {
    try {
      if (redissonClient == null) {
        log.info("DistributedRedisLock redissonClient is null");
        return false;
      }

      RLock lock = redissonClient.getLock(lockName);
      lock.unlock();
      log.info(
          "Thread [{}] DistributedRedisLock unlock [{}] success",
          Thread.currentThread().getName(),
          lockName);
      // 释放锁成功
      return true;
    } catch (Exception e) {
      log.error("DistributedRedisLock unlock [{}] Exception:", lockName, e);
      return false;
    }
  }
}


使用方法

 @Autowired private DistributedRedisLock redisLock;
 if(redisLock.lock(lockName))
 {
 try{
  //TODO:编写你的业务
 }
 finally{
  redisLock.unlock(lockName);
  }
 }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我可以为您提供有关于SpringBoot整合Redisson实现分布式的相关信息。 首先,您需要在您的SpringBoot项目中添加Redisson的依赖,可以在pom.xml文件中添加如下依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>${redisson.version}</version> </dependency> ``` 其中,`${redisson.version}`为Redisson的版本号。 接下来,在您的项目中创建一个RedissonConfig类,用于配置Redisson连接池和RedissonClient对象的实例化。示例代码如下: ```java @Configuration public class RedissonConfig { @Autowired private RedisProperties redisProperties; @Bean public RedissonClient redissonClient() { Config config = new Config(); String address = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort(); config.useSingleServer().setAddress(address).setDatabase(redisProperties.getDatabase()) .setPassword(redisProperties.getPassword()); return Redisson.create(config); } } ``` 在上述示例代码中,我们通过读取Redis的连接配置信息,使用单节点连接Redis。您也可以根据您的实际需要进行配置。 接下来,我们可以通过RedissonClient对象来获取分布式。示例代码如下: ```java @Autowired private RedissonClient redissonClient; public void acquireLock() { RLock lock = redissonClient.getLock("myLock"); lock.lock(); try { // 这里是您的业务逻辑代码 } finally { lock.unlock(); } } ``` 在上述示例代码中,我们首先通过`redissonClient.getLock("myLock")`获取一个名为"myLock"的分布式。然后,我们调用`lock.lock()`方法来获取,如果获取失败则会一直阻塞直到获取成功。在业务逻辑执行完成后,我们通过`lock.unlock()`方法来释放。 以上就是使用Redisson实现分布式整合方式。希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Top_雨夜聆风丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值