Redission入门

该文展示了如何在SpringBoot应用中集成Redisson进行分布式锁的实现。配置包括了项目依赖、application.yml文件的Redis设置,以及Redission配置类和Controller中的锁操作。通过Redisson,实现了线程间的同步,保证了并发场景下的数据一致性。
摘要由CSDN通过智能技术生成

1、依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.15.5</version>
        </dependency>
        <!--添加热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!--热部署配置-->
                <configuration>
                    <!--fork:如果没有该项配置,整个devtools不会起作用-->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

2、application.yml配置

spring:
  redis:
    database: 1  # Redis使用DB1
    timeout: 60000  # 相应超时时间:毫秒
    password: admin1234
    host: localhost
    port: 6379
server:
  port: 8081

3、Redission配置类

/**
 * @author DeyouKong
 * @description TODO
 * @date 2023/3/23 23:34
 */

@Configuration
public class MyRedissonConfig {

    @Value(value = "${spring.redis.host}")
    private String host;
    @Value(value = "${spring.redis.port}")
    private int port;
    @Value(value = "${spring.redis.database}")
    private int database;
    @Value(value = "${spring.redis.password}")
    private String password;

    /**
     * 单Redis节点模式配置方法
     * 其他配置參數,看:
     * <a href = "https://github.com/redisson/redisson/wiki/2.-%E9%85%8D%E7%BD%AE%E6%96%B9%E6%B3%95#26-%E5%8D%95redis%E8%8A%82%E7%82%B9%E6%A8%A1%E5%BC%8F">
     * 单Redis节点模式配置方法
     * </a>
     *
     * @return {@link RedissonClient}
     */
    @Bean(destroyMethod = "shutdown")
    RedissonClient redisson() {
        Config config = new Config();
        //Redis多节点
        // config.useClusterServers()
        //     .addNodeAddress("redis://127.0.0.1:6379", "redis://127.0.0.1:6380");
        //Redis单节点
        SingleServerConfig singleServerConfig = config.useSingleServer();
        //可以用"rediss://"来启用SSL连接
        String address = "redis://" + host + ":" + port;
        singleServerConfig.setAddress(address);
        //设置 数据库编号
        singleServerConfig.setDatabase(database);
        singleServerConfig.setPassword(password);
        //连接池大小:默认值:64
        // singleServerConfig.setConnectionPoolSize()
        return Redisson.create(config);
    }

}

4、Controller


/**
 * @author DeyouKong
 * @description TODO
 * @date 2023/3/24 20:38
 */

@RestController
@RequestMapping("/redission")
public class RedissionController {

    @Resource
    private RedissonClient redissonClient;

    private final static String LOCK="I_AM_LOCK";

    @GetMapping("/list")
    public String getString(){
        // 1、获取一把锁,只要锁的名字一样,既是同一把锁
        RLock lock = redissonClient.getLock(LOCK);
        // 2、加锁

        lock.lock(10, TimeUnit.NANOSECONDS);     // // 阻塞式等待

        try {
            System.out.println(Thread.currentThread().getName()+":\t 获得锁");
            Thread.sleep(50000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 3、解锁
            lock.unlock();
            System.out.println(Thread.currentThread().getName()+":\t 释放锁锁");
        }
        return "123";
    }

    // 并发写测试
    @GetMapping("write")
    public String writeValue(){
        RReadWriteLock myLock = redissonClient.getReadWriteLock ("my_lock");
        RLock rLock = myLock.writeLock ( );
        rLock.lock ();
        String s = "";
        try {
            System.out.println ("写锁加锁成功..."+Thread.currentThread ().getId () );
            s= UUID.randomUUID ().toString ();
            TimeUnit.SECONDS.sleep (5);
        } catch (Exception e) {
            e.printStackTrace ( );
        }
        finally {
            System.out.println ("写锁解锁成功..."+Thread.currentThread ().getId () );
            rLock.unlock ();
        }
        return s;
    }

    // 并发读测试
    @GetMapping("read")
    public String readValue(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("my_lock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock ();
        String s = "";
        try {
            System.out.println ("读锁加锁成功..."+Thread.currentThread ().getId () );
            s = "345";
            Thread.sleep(3000);
//            s = (String) redisTemplate.opsForValue ().get ("writeValue");
        } catch (Exception e) {
            e.printStackTrace ( );
        }finally {
            System.out.println ("读锁解锁成功..."+Thread.currentThread ().getId () );
            rLock.unlock ();
        }
        return s;
    }

}

5、启动类

@SpringBootApplication
public class RedissionDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedissionDemoApplication.class, args);
    }

}

6、测试

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值