Redisson分布式锁框架

Redisson分布锁原理分析及源码解读 Redisson使用信号量控制,每次收到解锁消息仅释放一个信号,只允许一个线程解除阻塞状态,去竞争锁(参考LockPubSub类的onMessage方法),当然,如果线程等待超时(超过锁过期时间)也会重新加入锁竞争行列。tryLock方法为尝试获取锁的方法入口,返回ttl表示锁剩余超时时间,如果返回null,表示无人占有锁,当前线程获取锁成功,如果获取锁成功,客户端会启动一个看门狗线程,来自动为锁续期(后面会讲到看门狗作用)。如果锁快要过期了,客户端还占有锁,那么就自动给锁续期,延长锁的过期时间。 阅读详情

        Redisson是一个用于Redis的Java客户端,它极大地简化了分布式锁、分布式集合、分布式服务等复杂场景下的开发工作。Redisson提供了丰富的功能,并且对分布式锁的支持尤为强大和灵活。

引入依赖

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.20.0</version>
</dependency>

创建配置类

@Configuration
public class RedissonConfig {

    @Bean("redissonClient")
    public RedissonClient redissonClient() {
        Config config = new Config();
        String redisHost = "127.0.0.1";
        String password = "Aa123456@";
        Integer port = 6379;
        int dbNo = 0;
        config.useSingleServer()
                .setAddress("redis://" + redisHost + ":" + port)
                .setDatabase(dbNo)
                .setPassword(password);
        // 创建RedissonClient对象
        return Redisson.create(config);
    }

}

方式1:基本使用(自动续期)
lock.lock();

方式2:指定租约时间(无自动续期)
对象.lock(10, TimeUnit.SECONDS);

方式3:尝试获取锁(推荐)
boolean acquired = 对象.tryLock(10, 30, TimeUnit.SECONDS);

1.可重入锁(Reentrant Lock)

        是最常用的锁类型之一,类似于Java中的ReentrantLock。

        在某些复杂的业务逻辑中,一个方法可能会调用另一个方法,而这两个方法都需要获取同一把锁。如果使用普通的锁,线程在第一次获取锁后,再次尝试获取锁时会被阻塞。可重入锁允许同一个线程多次获取锁,避免了这种情况。

    private RedissonClient redissonClient;

    public void performTask() throws InterruptedException {
        RLock lock = redissonClient.getLock("myLock");
        try {
            // 尝试获取锁,最多等待10秒,持有锁的时间为60秒
            boolean isLocked = lock.tryLock(10, 60, TimeUnit.SECONDS);
            if (isLocked) {
                // 执行业务逻辑
            }
        } finally {
            lock.unlock(); // 确保释放锁
        }
    }

2.公平锁(Fair Lock)

        公平锁确保所有请求按照它们到达的顺序获取锁,避免“饥饿”现象。

    private RedissonClient redissonClient;

    public void performTask() throws InterruptedException {
        RLock fairLock = redissonClient.getFairLock("myFairLock");

        try {
            fairLock.lock(10, TimeUnit.SECONDS); // 获取锁并设置最大等待时间
            //fairLock.tryLock(10,60,TimeUnit.SECONDS);
            // 执行业务逻辑
        } finally {
            fairLock.unlock();
        }
    }

3.读写锁(ReadWriteLock)

        读写锁允许多个线程同时读取数据,但在写入时提供独占访问。

    private RedissonClient redissonClient;

    public void read() throws InterruptedException {
        //获取读写锁对象
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("myReadWriteLock");

        rwLock.readLock().lock();
        try {
            // 执行读操作
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void write() throws InterruptedException {
        //获取读写锁对象
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("myReadWriteLock");

        rwLock.writeLock().lock();
        try {
            // 执行写操作
        } finally {
            rwLock.writeLock().unlock();
        }
    }

4.联锁(MultiLock)

        联锁是一种同步机制,用于同时获取多个锁。在分布式系统中,当需要对多个独立资源进行操作时,联锁确保所有的资源都被锁定,以进行安全的原子操作。

    private RedissonClient redissonClient;
    
    public void performTask() throws InterruptedException {
        RLock lock1 = redissonClient.getLock("lock1");
        RLock lock2 = redissonClient.getLock("lock2");

        RLock multiLock = redissonClient.getMultiLock(lock1, lock2);

        try {
            multiLock.lock();
            // 执行业务逻辑
        } finally {
            multiLock.unlock();
        }
    }

5.自旋锁(Spin Lock)

        自旋锁是一种非阻塞锁,线程在获取锁时会不断尝试,直到成功为止。

    private RedissonClient redissonClient;

    public void performTask() throws InterruptedException {
        RLock spinLock = redissonClient.getSpinLock("mySpinLock");
        try {
            spinLock.lock();
            // 执行业务逻辑
        } finally {
            spinLock.unlock();
        }
    }

7.红锁(RedLock)

        在多个独立的 Redis 节点上同时获取锁,只有当大多数节点(N/2 + 1)都成功获取锁时,才认为锁获取成功。

        备注:当你在类的构造器、字段(成员变量)或 setter 方法上使用 @Autowired 时,Spring 容器会尝试找到匹配的 Bean 并将其注入到相应的属性中。这极大地简化了对象之间的依赖管理,减少了样板代码,并提高了代码的可维护性和灵活性。

        创建多节点配置类

@Configuration
public class RedissonConfig {
    @Bean(name = "client1", destroyMethod = "shutdown")
    public RedissonClient createClient1() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379")
                .setPassword("password1") // 如果有密码
                .setDatabase(0); // 选择数据库
        return Redisson.create(config);
    }

    @Bean(name = "client2", destroyMethod = "shutdown")
    public RedissonClient createClient2() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6380")
                .setPassword("password2") // 如果有密码
                .setDatabase(0); // 选择数据库
        return Redisson.create(config);
    }

    @Bean(name = "client3", destroyMethod = "shutdown")
    public RedissonClient createClient3() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6381")
                .setPassword("password3") // 如果有密码
                .setDatabase(0); // 选择数据库
        return Redisson.create(config);
    }
}

        实现工具类

@Component
public class RedissonUtil {

    private final RedissonClient client1;
    private final RedissonClient client2;
    private final RedissonClient client3;

    @Autowired
    public RedissonUtil(@Qualifier("client1") RedissonClient client1,
                        @Qualifier("client2") RedissonClient client2,
                        @Qualifier("client3") RedissonClient client3) {
        this.client1 = client1;
        this.client2 = client2;
        this.client3 = client3;
    }

    public boolean tryRedLock(String lockName, long waitTime, long leaseTime, TimeUnit timeUnit) {
        RLock lock1 = client1.getLock(lockName);
        RLock lock2 = client2.getLock(lockName);
        RLock lock3 = client3.getLock(lockName);

        RLock redLock = client1.getRedLock(lock1, lock2, lock3);

        try {
            return redLock.tryLock(waitTime, leaseTime, timeUnit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void releaseRedLock(String lockName) {
        RLock lock1 = client1.getLock(lockName);
        RLock lock2 = client2.getLock(lockName);
        RLock lock3 = client3.getLock(lockName);

        RLock redLock = client1.getRedLock(lock1, lock2, lock3);
        if (redLock.isLocked() && redLock.isHeldByCurrentThread()) {
            redLock.unlock();
        }
    }
}

        代码示例

@Service
public class RedisService {

    private final RedissonUtil redissonUtil;

    @Autowired
    public RedisService(RedissonUtil redissonUtil) {
        this.redissonUtil = redissonUtil;
    }

    public void performTask() throws InterruptedException {
        boolean isLocked = redissonUtil.tryRedLock("myRedLock", 100, 10, TimeUnit.SECONDS);
        if (isLocked) {
            try {
                System.out.println("RedLock acquired successfully!");
                // 执行业务逻辑
                Thread.sleep(1000L);
            } finally {
                redissonUtil.releaseRedLock("myRedLock");
                System.out.println("RedLock released!");
            }
        } else {
            System.out.println("Failed to acquire RedLock!");
        }
    }
}

Redisson 自旋锁(Spin Lock)详解与应用 自旋锁(Spin Lock)是一种不断循环尝试获取锁的实现方式。与传统的阻塞锁不同,自旋锁不会让线程进入等待状态,而是通过循环不断尝试获取锁,直到成功为止。这种方式适用于锁竞争频繁但持有时间非常短的场景。在 Redisson 中,自旋锁并不是一个单独的类,而是可以通过设置来实现自旋方式的锁获取。某些版本中可能会单独命名为SpinLock。 阅读详情

相关推荐

分布式锁框架-Redisson

Redisson是架设在Redis基础上的一个Java驻内存数据网格(In-Memory Data Grid)。Redisson在基于NIO的Netty框架上,充分的利用了Redis键值数据库提供的一系列优势,在Java实用工具包中常用接口的基础上,为使用者提供了一系列具有分布式特性的常用工具类。使得原本作为协调单机多线程并发程序的工具包获得了协调分布式多机多线程并发系统的能力,大大降低了设计和研发大规模分布式系统的难度。同时结合各富特色的分布式服务,更进一步简化了分布式环境中程序相互之间的协作。

Roc的博客 1730

【面试 分布式锁详细解析】续命 自旋锁 看门狗 重入锁,加锁 续命 解锁 核心源码,lua脚本解析,具体代码和lua脚本如何实现

【面试 分布式锁详细解析】续命 自旋锁 看门狗 重入锁,加锁 续命 解锁 核心源码,lua脚本解析,具体代码和lua脚本如何实现

qq120631157的博客 1287

云原生微服务之分布式锁框架 Redisson

Redisson 在基于 NIO 的 Netty 框架上,充分的利⽤了 Redis 键值数据库提供的⼀系列优势,在Java 实⽤⼯具包中常⽤接⼝的基础上,为使⽤者提供了⼀系列具有分布式特性的常⽤⼯具类。使得原本作为协调单机多线程并发程序的⼯具包获得了协调分布式多机多线程并发系统的能⼒,⼤⼤降低了设计和研发⼤规模分布式系统的难度。同时结合各富特⾊的分布式服务,更进⼀步简化了分布式环境中程序相互之间的协作。

Java 技术专栏,从入门到精通,熟悉企业级开发 9469

redissonclient类_Redisson的使用

java分布式锁

gb4215287的博客 9722

qupath再度更新:使用WSInfer进行深度学习

我们在下面提供了一个示例,说明如何使用 WSInfer 创建 WSI 中肿瘤和肿瘤浸润淋巴细胞 (TIL) 的空间图谱,这些图谱被认为在几种癌症中既有预后又有预测意义6,10,11,12.由于 WSI 非常大,因此它们通常被分解为补丁,以使分析变得可行。补丁分类的输出通常是空间分类地图,通常可以跨 WSI 集成,以创建表示该幻灯片的诊断、预测或“分数”的单个输出。在当前的实施中,我们专注于斑块分类的通用任务,该任务广泛用于广泛的病理学应用,具有促进诊断、预后或预测功能的深度学习模型。

hx2024的博客 2200

PotPlayer终极画质调校:深入MadVR渲染器设置,让你的显示器发挥100%潜力

本文深入探讨了如何通过MadVR渲染器优化PotPlayer的画质设置,充分发挥高端显卡和显示器的潜力。从色彩空间匹配、色深优化到HDR元数据处理,提供了一套完整的配置指南,帮助用户实现影院级视觉体验。特别适合拥有NVIDIA RTX或AMD RX系列显卡的用户进行精细调校。

weixin_42530458的博客 600

redisson基础bean创建

原文出处:https://blog.youkuaiyun.com/u010730731/article/details/110002512 单机模式 @Bean public RedissonClient redissonClient() { RedissonClient redisson = Redisson.create(); Config config = new Config(); config.useSingleServer().setAddress("redis://127.0.0.1:6379");

qq_37809967的博客 2154

OpenSpec 从入门到精通:AI 时代的最佳 SDD 范式

同样都是「先写规范再写代码」的开源 SDD 框架,OpenSpec(https://github.com/fission-ai/openspec) 展现出了极高的工程性价比,无论是使用 Claude Code、Cursor 还是 Aider,都可以无缝接入 OpenSpec 的规格管理层。这些问题需要人来做判断,AI 做不了这个主。整个流程跑下来,OpenSpec 产出的效果还是令人满意的,一些前期没有考虑到的细节 AI 都补上了,生成的相关文档也有利于开发人员的知识对齐,可以尝试在团队内部推广。

qq_39093474的博客 929

Redisson—分布式锁框架

一、 Redisson介绍 Redisson在基于NIO的Netty框架上,充分的利用了Redis键值数据库提供的⼀系列优势,为使用者提供了⼀系列具有分布式特性的常用⼯具类。 一款基于Redis+看门狗机制的分布式锁框架 二、 Redisson工作原理 看门狗机制 三、 Redisson使用 添加依赖 <dependency> <groupId>org.redisson</groupId> <artifactId>redisson&lt

许久 974

Ubuntu安装opencv4.5(自己安装过程详细)

1.下载opencv 在opencv官网下载source版,下载链接 http://opencv.org/releases.html。别下载错版本 下载过程就不多说了。 2.安装过程 2.1解压 unzip opencv-4.5.0.zip cd opencv-4.5.0 2.2安装依赖的库 sudo apt-get install cmake sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-

weixin_45629790的博客 1万+

批量导入经纬度点到奥维地图中

随便说说 最近出来出差,天天东奔西跑的,跑完了回到酒店还得整理一天的成果,基本上晚上9点才能整理完,累的基本上倒头就睡,没时间鼓捣自己喜欢的东西了。但想着也得写点啥吧,想来想去就那最近工作中用到的东西吧。因为我们现在的工作内容呢,基本上就是按照着上面给的地理位置找到地方开始检查。所以呢,就需要批量的把手上的经纬点信息导入到地图中,安排好路线,利用导航高效的找到地方。给的坐标就是gps点,wgs-84的,使用奥维地图最方便了,不用做坐标转换直接能用。所以作为组里的gis担(苦)当(力),这个导坐标的活就由我来

lionhenryzxxy的博客 3万+

Redisson 框架中的分布式锁

实现分布式锁通常有三种方式:数据库、Redis 和 Zookeeper。我们比较常用的是通过 Redis 和 Zookeeper 实现分布式锁。Redisson 框架中封装了通过 Redis 实现的分布式锁,下面我们分析一下它的具体实现。

e_watermelons的博客 1211

逆向拆解dy接口a_bogus 1.0.1.19版本核心算法(纯算版)第二部分

本文深入解析了dy接口a_bogus 1.0.1.19版本的核心算法,重点介绍了逆向分析的基础方法论、魔改Base64编码识别与还原、随机数生成与位运算解析等关键技术。通过详细的代码示例和实用技巧,帮助开发者掌握逆向工程中的关键步骤,特别是针对a_bogus参数的生成逻辑和混淆处理。

weixin_29288313的博客 408

Redisson 分布式锁框架

如果线程一在Redis的master节点上拿到了锁,但是加锁的key还没同步到slave节点。恰好这时,master节点发生故障,一个slave节点就会升级为master节点。线程二就可以获取同个key的锁啦,但线程一也已经拿到锁了,锁的安全性就没了。并且这些master节点是完全相互独立的,相互之间不存在数据同步。同时,需要确保在这多个master实例上,是与在Redis单实例,使用相同方法来获取和释放锁。为了解决这个问题,Redis作者 antirez提出一种高级的分布式锁算法:Redlock。

weixin_46668257的博客 439

二极管钳位电路、限幅电路和检波电路Multisim电路仿真

本文系统介绍了二极管钳位、限幅和检波三种基础电路的工作原理及Multisim仿真验证。钳位电路通过电容-二极管配合实现波形整体平移,将波峰或波谷固定在指定电压;限幅电路利用二极管导通特性削除信号超出设定阈值的部分;检波电路则通过半波整流和电容滤波从调幅波中提取音频信号。三种电路均通过Multisim仿真验证了理论分析结果,展示了二极管在信号处理中的关键作用。这些基础电路广泛应用于信号调理、电平保护和通信解调等领域。

XU157303764的博客 1122

【项目实战】AES实施应符合NIST密码算法验证程序

AES由美国国家标准与技术研究院(NIST)制定。NIST是负责开发和维护美国政府使用的技术标准的机构,包括加密标准。

奶爸的编程之路,也就一周冷个三天 766

使用Redisson框架实现分布式锁

之前讲了基于Redis原子操作实现Redis锁,代码比较冗余而且有缺陷,Redis官方推荐Redisson,Redisson提供了很多分布式操作服务,直接调用封装好的API操作,代码更直观。 1. 添加依赖 <dependency> <groupId>org.redisson</groupId> &...

unclecoco的博客 760

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

分布式锁以及分布式锁框架Redisson

1、乐观锁与悲观锁乐观锁悲观锁2、可重入锁和非可重入锁可重入锁:当在一个线程中第一次成功获取锁之后,在此线程中就可以再次获取非可重入锁3、公平锁和非公平锁公平锁:按照线程的先后顺序获取锁非公平锁:多个线程随机获取锁4、阻塞锁和非阻塞锁阻塞锁:不断尝试获取锁,直到获取到锁为止非阻塞锁:如果获取不到锁就放弃,但可以支持在一定时间段内的重试​ ——在一段时间内如果没有获取到锁就放弃。

qq_60796259的博客 1215

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

分布式锁框架--Redisson

分布式锁框架--Redisson

yunli0的博客 820

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Redisson 框架使用redis分布式锁

在 Redis 单实例或哨兵模式下,如果主节点宕机,即使有从节点,也可能因主从异步复制导致锁丢失(客户端A在主节点拿到锁,但锁还未同步到从节点,主节点就宕机了,从节点升级为主后没有这把锁,客户端B又能获取锁)。

JAVA领域优质创作者,基于分片网络查询方法专利发明者。 513

基于Redisson框架实现分布式锁的代码实现

基于Redisson框架实现分布式锁的代码实现

qq_27735079的博客 506

Redisson:这么强大的实现分布式锁框架,你还没有?

摘要:Redisson框架十分强大,基于Redisson框架可以实现几乎你能想到的所有类型的分布式锁。

华为云官方博客 1249

基于 Redis NX 和 Redisson 实现分布式锁:从手动实现到框架应用

Redis 的 SET 命令提供了 NX(Only set the key if it does not already exist)选项,非常适合用来实现分布式锁的获取操作。Redisson 是一个基于 Redis 的 Java 分布式框架,提供了完善的分布式锁实现,解决了手动实现的诸多问题。

2501_91015529的博客 743

Redis实现分布式锁原理和Redisson框架实现分布式锁,全网最详细讲解

分布式锁,即分布式系统中的锁。在单体应用中我们通过锁解决的是控制共享资源访问的问题,而分布式锁,就是解决了分布式系统中控制共享资源访问的问题。与单体应用不同的是,分布式系统中竞争共享资源的最小粒度从线程升级成了进程。

我认不到你的博客 2887

spring boot 下 Redisson分布式锁框架简单使用

在项目中要用到分布式锁,之前都是用jedis去实现的,有很多细节方面都有可能出问题,然后在了解到了redisson之后,决定使用这个成熟的框架去实现分布式锁。 首先引入jar包,除了spring boot的相关jar包,只引这一个就够了 <dependency> <groupId>org.redisson</gr...

lvqinglou的博客 600
上一篇: Java 分布式锁
下一篇: Java 事务:@Transactional 、@GlobalTransactional
快乐吃手手  :  )
博客等级 码龄6年 119粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值