curator(zookeeper)实现分布式锁简单代码

Zookeeper实战-使用Curator实现Leader选举 分布式系统中,对于一个复杂的任务,我们经常会选举一个Master节点,借助zk我们可以轻易的实现此项任务,在kafka以及spark的standalone模式下都是使用zk来实现Master选举,本文先从原理方面介绍为什么zk可以实现Master选举,然后利用curator的api进行Master选举实战。 zk进行Master选举原理 zookeeper的节点有两种类型: 持久节点和临时节点... 阅读详情

curator是对zookeeper进行了封装,可以实现分布式锁功能
1.基本原理,zookeeper是dataTree结构,每个节点是一个znode,znode有四种类型,
持久节点(客户端断开连接后znode不会删除),
临时节点(客户端断开连接后znode删除)
持久顺序节点(创建节点时,Zookeeper会根据创建的时间顺序给该节点名称进行编号,持久的)
临时顺序节点(创建节点时,Zookeeper会根据创建的时间顺序给该节点名称进行编号,临时的)

分布式锁就是利用了其中的临时顺序节点来实现的,原理如下:
先创建一个持久znode,连接进来的客户端如果想获得锁就要在这个持久znode下面创建子znode,创建之后客户端会把所有的znode都遍历一遍,看一下自己的znode编号是不是最小的,如果是最小的就获得锁,如果不是最小的,那么就watch他前面的那一个节点避免羊群效应(锁释放后,所有的client都去抢锁),当一个client执行完之后会把自己的znode删除,这时候他后面的znode会收到消息,遍历一遍看自己是不是最小的(既然收到消息,那此时当然是最小的),是最小的,然后就获得锁,以此类推

本节讲一下可重入锁

2.具体代码实现
创建一个springboot工程,导入依赖,和application.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.levi</groupId>
    <artifactId>zk-code</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-client -->
<!--        <dependency>-->
<!--            <groupId>org.apache.curator</groupId>-->
<!--            <artifactId>curator-client</artifactId>-->
<!--            <version>4.2.0</version>-->
<!--        </dependency>-->

        <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.2.0</version>
        </dependency>
        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--        mysql连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <!--        自动生成代码-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--        velocity模板-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <!--        swagger-->
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--swagger-bootstrap-ui-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>



</project>
spring:
  profiles:
    active: dev # 环境设置
  application:
    name: service-core # 服务名
  datasource: # mysql数据库连接
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://host:3306/seckill?serverTimezone=GMT%2B8&characterEncoding=utf-8
    username: root
    password: root

#mybatis xml文件地址
#mybatis-plus:
#  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#    mapper-locations: classpath:com/levi/mapper/xml/*.xml


zookeeper:
  lockpath: /parent-lock/lock
  address: host:2181

启动类

package com.levi;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = {"com.levi.mapper"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

数据库建表,简单测试
id,商品名称,库存在这里插入图片描述
mybstisplus逆向生成工具

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

/**
 * @ClassName CodeGenerator
 * @Description TODO
 * @Author Levi
 * @Date 2021/4/14 10:41
 **/
public class CodeGenerator {
    @Test
    public void genCode() {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("levi");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setServiceName("%sService");	//去掉Service接口的首字母I
        gc.setIdType(IdType.AUTO); //主键策略
        gc.setSwagger2(true);//开启Swagger2模式
        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.177.129:3306/seckill?serverTimezone=GMT%2B8&characterEncoding=utf-8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("St1282001316*");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.levi");
        pc.setEntity("pojo"); //此对象与数据库表结构一一对应,通过 DAO 层向上传输数据源对象。
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok
        strategy.setLogicDeleteFieldName("is_deleted");//逻辑删除字段名
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);//去掉布尔值的is_前缀(确保tinyint(1))
        strategy.setRestControllerStyle(true); //restful api风格控制器
        mpg.setStrategy(strategy);

        // 6、执行
        mpg.execute();
    }
}

创建service接口,并且实现里面的方法

package com.levi.service;

public interface SecKillService {

    boolean buyProduct(Integer id, Integer quantity) throws Exception;
}

实现类

package com.levi.service.impl;

import com.levi.mapper.ProductMapper;
import com.levi.pojo.Product;
import com.levi.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀主要逻辑在这个里面
 */
@Service
@Slf4j
public class SecKillServiceImpl implements SecKillService {

    @Value("${zookeeper.lockpath}")
    private String lockpath;

    @Value("${zookeeper.address}")
    private String address;


    @Resource
    private ProductMapper productMapper;

    @Override
    public boolean buyProduct(Integer id, Integer quantity) throws Exception {
        RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework zookeeperClient = CuratorFrameworkFactory.newClient(address, 60000, 15000, retry);
        zookeeperClient.start();
        // create lock
        InterProcessMutex lock = new InterProcessMutex(zookeeperClient, lockpath);
        //等待2秒看有没有得到锁
        if ( lock.acquire(2,TimeUnit.SECONDS) ) {
            log.info("{}抢到了锁",Thread.currentThread().getId());
            try {
                // do some work inside of the critical section here
                Product product = productMapper.selectById(1);
                if (product.getStack() == 0 || product.getStack()<quantity) {
                    return false;
                }
                product.setStack(product.getStack() - 1);
                productMapper.updateById(product);
            }catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.release();
                log.info("{}释放了锁",Thread.currentThread().getId());
            }
        }else{
            //没有得到锁,直接返回false
            return false;
        }
        return true;
    }
}

创建controller测试,每个人买一个商品

package com.levi.controller;

import com.levi.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("zk")
@Slf4j
public class SecKillController {

    @Autowired
    private SecKillService secKillService;

    @GetMapping("secKill")
    public void secKill() throws Exception {
        if (!secKillService.buyProduct(1, 1)) {
            log.info("{}购买时候商品库存不足",Thread.currentThread().getId());
            System.out.println();
        }else {
            log.info("{}购买商品成功",Thread.currentThread().getId());
        }
    }

}

启动类,启动

package com.levi;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = {"com.levi.mapper"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

使用jmeter测试,创建10个线程,每个人买一个,但是数据库只有5个
在这里插入图片描述

在这里插入图片描述
最后只有5个购买成功
在这里插入图片描述
总结:zookeeper的锁力度大,redis的锁快

Curator与zookeeper版本问题,分布式锁 pom.xml如下: <!-- zookeeper --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.8</version> 阅读详情

相关推荐

缓存架构SpringBoot集成Curator实现zookeeper分布式锁

一、分布式锁简介 1、什么是锁 在单机环境下,当存在多个线程可以同时改变某个共享变量时,就需要同步来实现该功能,使其线程安全。 而同步就是通过锁来实现的。锁保证了同一时刻只有一个线程来修改共享变量。 在单机环境下,Java提供了一些并发安全包可以一定程度上保证线程安全,但是在分布式环境(多机环境)下,这些并发包显得就无能为力了!! 2、什么是分布式 分布式的CAP理论: 任何一个分布式系统都无法...

zhuguanghalo的博客 6845

基于Curator(zookeeper)实现leader选举

在分布式计算中,leader election是很重要的一个功能,这个选举过程是这样子的:指派一个进程作为组织者,将任务分发给各节点。在任务开始前,哪个节点都不知道谁是leader或者coordinator。当选举算法开始执行后,每个节点最终会得到一个唯一的节点作为任务leader。除此之外,选举还经常会发生在leader意外宕机的情况下,新的leader要被选举出来,如下图所示,这个就是所谓的leader选举,而zookeeper作为leader选举的功能,在很多中间件中都有使用,比如kafka基于zoo

Java是世界上最好的语言 4052

springboot基于zookeeper实现分布式锁

参考链接: https://blog.csdn.net/wuzhiwei549/article/details/80692278 https://blog.52itstyle.vip/archives/3202/ 先说明一下zookeeper实现分布式锁的原理,这里参看csdn一篇非常好的文章,如果不想看原理直接跳过看后面的具体代码实现 单机应用架构中,秒杀案例使用ReentrantLcok或者s...

holmes369的博客 3453

分布式锁实现方案

当多个进程在不同的系统中,就需要使用分布式锁控制多个进程对同一个资源的访问。本篇介绍的是通过 Redis 实现的分布式锁。

一叶知秋的博客 1万+

使用sklearn学习多项式回归(三)

1,什么是线性 我们无数次提到”线性“这个名词。在支持向量机中,我们也曾经提到最初的支持向量机只能够分割线性可分的数据,然后引入了”核函数“来帮助我们分类那些非线性可分的数据。我们也曾经说起过,比如说决策树,支持向量机是”非线性“模型。所有的这些概念,让我们对”线性“这个词非常熟悉,却又非常陌生——因为我们并不知道它的真实含义。接下来我们看看线性回归模型改进的核心之一:帮助线性回归解决非线性问题。 1.1,变量之间的线性关系 ”线性“这个词用于描述不同事物时有着不同的含义。我们最常使用的线性是指“变量

理科男同学 5100

论文笔记--Spatial-Temporal Fusion Graph Neural Networks for Traffic Flow Forecasting

Summary 在交通预测问题上,现有的框架通常利用给定的空间邻接图和复杂的机制来建模空间和时间关联。作者认为使用给定的空间邻接图会限制模型的有效时空相关性学习,并且它们通常使用单独的模块来实现空间和时间相关性,或者只使用独立的组件来捕获局部或全局的异质依赖关系,割裂了时空依赖关系。为此作者提出一种时空融合图神经网络用于交通预测。提出一种数据驱动的“时间图”生成方法,以此来补偿空间图可能没有反映的相关性。提出一种新的交通预测方法。 Problem Definition 交通预测中的挑战 以上图为

chenxino的博客 1755

Curator zookeeper 分布式锁实现

curator版本: &lt;dependency&gt; &lt;groupId&gt;org.apache.curator&lt;/groupId&gt; &lt;artifactId&gt;curator-recipes&lt;/artifactId&gt; &lt;version&gt;2....

abc123maxiaolong的专栏 248

Windows下快速搭建Kettle开发环境:基于9.4.0.0版本的保姆级教程

本文提供Windows系统下Kettle 9.4.0.0开发环境的详细搭建指南,涵盖源码获取、Maven配置优化、高效编译及部署运行全流程。通过实战验证的步骤和常见问题解决方案,帮助数据工程师快速完成环境配置,提升ETL开发效率。

weixin_28829479的博客 329

开源客户端Curator 使用(下)

一 新建curatorupdatedata 1 代码 package com.cakin.zookerper; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFramew

实践求真知 481

TSEND_C指令错误代码解析与实战排错指南

本文详细解析西门子PLC中TSEND_C指令的常见错误代码,包括连接建立、参数配置、资源限制和网络通信等错误类型。针对错误代码80C4等典型问题提供实战排错指南,帮助工程师快速诊断和解决工业通信中的连接故障,提升系统可靠性。

backprop5master的博客 410

硬件手册——PT100精密测温电路

PT100精密测温电路 一、需求分析 根据题目要求为:测温范围为0-100℃、测温精度要求为±1℃。由于铂电阻具有精度高、性能可靠、稳定性好的特点,且铂电阻的电阻相对变化率与温度的关系曲线线性度最好,故选择铂电阻作为敏感元件。而在国标中,铂电阻有几种不同的标准,如PT100、PT1000。分别对应着0摄氏度下铂电阻的阻值为100R和1000R,由于需要考虑铂电阻的自发热问题,所以尽量选择阻值小的铂电阻,故选择PT100为最终型号。 二、电路设计 2.1 热电阻接法 热电阻测温电路有多种接法,其中三线制会导致

weixin_41655430的博客 5万+

基于Zookeeper实现分布式锁

一、Zookeeper相关概念 基于Zookeeper实现分布式锁,主要依赖于它的【瞬时有序节点】,当多个客户端并发创建瞬时有序节点时,会自动为我们生成有序的节点,例如定义子节点名为 order_ ,则生成的节点为 order_00000001,下一个节点为order_00000002,为我们保证有序。 利用Zookeeper节点的递增性,可以规定节点编号最小的那个获得锁。当编号最小的那个释放锁后,通知第二个节点获得锁(节点监听机制),以此类推,首尾相连。所以说Zookeeper天然支持分布式锁。 ..

dwhhome的博客 371

栅极驱动电路设计(一)

SiC驱动电路设计需满足更高标准,重点包括:驱动电压需18~20V开通、-3~-5V关断;栅极电阻优选5~10Ω以平衡开关性能与可靠性;必须集成欠压保护(阈值11~15V)和快速短路保护。多电平驱动控制通过动态调节栅压和驱动强度优化性能,如前期弱驱动抑制振荡,后期强驱动降低损耗。以NCE120ED65VTP4为例,栅压从18V提升至20V可使导通损耗降低15%。相比传统方案,有源驱动(含数字分段和模拟闭环控制)能更灵活地提升开关速度与效率。

嵌入式老牛的博客 448

ZK分布式锁的实现

ZK分布式锁的实现 1. 类图 2. 实现 2.1 简单实现 通过实现抽象实现AbstractLock,实现共有逻辑 简单实现的想法是每次都监听一个节点,当节点失效的时候通过Zk的监听模式通知客户端来重新争取锁。 AbstractLock public abstract class AbstractLock { public final static String PATH = "/MYLOCK3"; public static final String ADDRESS = "12

zrqsyh的博客 305

基于Simulink的单级式光伏并网系统MPPT控制仿真

本文基于Simulink平台,详细介绍了单级式光伏并网系统的MPPT控制仿真实现。主要内容包括:1)阐述MPPT作为光伏系统"智能大脑"的核心作用;2)解析单级式系统架构及扰动观察法(P&O)算法原理;3)以10kW户用系统为例,分步骤演示建模过程,包括光伏阵列搭建、P&O控制器实现(含MATLAB代码)、并网控制设计等;4)通过仿真验证系统在光照突变下的动态响应性能,MPPT效率达98.3%。文章还提出了变步长P&O等优化方向,为光伏系统仿真与控制提供实用指导。

xiaoheshang_123的博客 111

图神经网络实战——利用节点回归预测网络流量

在机器学习中,回归指的是对连续值的预测。通常与分类形成鲜明对比,分类的目标是找到正确的类别(即离散值,而非连续值)。在图数据中,分类和回归分别对应于节点分类和节点回归。在本节中,我们将尝试预测每个节点的连续值,而非分类变量。

盼小辉丶的博客 1万+

基于zookeeper实现分布式锁

前言 在分布式锁的实现中,zookeeper也是一种不错的选择,了解zookeeper的同学应该知道,zookeeper不仅可以作为集群的部署的中间件的服务协调器,器本身也是具有一定的数据存储结构的,有点类似于文件的分层结构,但是它们本身是有序的 基于它的存储数据的文件结构特性,可以利用zookeeper实现分布式锁,具体来说,其实现原理如下: 利用zookeeper的临时有序节点的特性【zookeeper的节点类型】 多线程并发创建临时节点时,得到的节点序列是有序的 序号最小的那个线程获得锁 其他线程则

congge 1126

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Zookeeper简单介绍及实现一个最简单的分布式锁

目录 前言 1、Zookeeper是什么? 2、Zookeeper的数据模型 3、Zookeeper基本概念 4、Zookeeper特性 5、Zookeeper常用的功能 6、基于简单互斥锁实现分布式锁代码实现 7、基于Curator实现分布式锁 前言 第一个例子是基于zkclient客户端实现的分布式锁(即选主),利用的是Zookeeper的临时节点在宕机后被删除这一特性实现...

清茶的博客 668

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Zookeeper Curator 简单实现;监听Watcher;分布式事务,分布式计数器

引入jar包 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0

qq_39246466的博客 271

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

zookeeper实现分布式锁,吊打面试官

前言我们之前讲了很多锁的只用,比如synchonrized、ReentrantLock、AQS等等。这些都是单体应用下锁的一些使用。众所周知,我们现在的应用都是分布式的。所以上面那些锁已经...

hnjsjsac的博客 224

springboot2整合zookeeper集成curator

步骤: 1- pom.xml <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.12....

weixin_30314813的博客 636

图解curator如何实现zookeeper分布式锁

curator提供的四种分布式锁概述(InterProcessMutex、InterProcessSemaphoreMutex、InterProcessReadWriteLock、InterProcessMultiLock),Zookeeper分布式锁实现思路,Zookeeper分布式锁解决的问题,Zookeeper分布式锁优缺点,InterProcessMutex实现zookeeper分布式原理/源码解析,图解curator解锁 / 解锁流程

健身变秃,coding变强 1万+

Zookeeper(curator)实现分布式锁案例

Zookeeper下载安装、Zookeeper常用命令、zookeeper实现分布式锁案例、curator实现分布式案例、zookeeper实现分布式锁思想

健身变秃,coding变强 1万+

zookeeper实现分布式锁-curator

前言 在之前《Redis实现分布式锁》一文中我已经介绍了使用Redis实现分布式锁原理,今天主要是介绍一下如何使用zookeeper实现分布式锁。 一.zookeeper介绍和安装 1.zookeeper介绍 1.1.什么是zookeeper ZooKeeper由雅虎研发,是Google Chubby的开源实现,目前托管给Apache,是一个经典的分布式数据一致性解决方案,致力于为分布式应用提供一个高性能、高可用,且具有严格顺序访问控制能力的分布式协调服务。 分布式应用程序可以基于ZooKeeper实现数

墨家巨子@俏如来 2921

ZooKeeper框架Curator分布式锁实现及源代码分析

本原创入门教程,涵盖ZooKeeper核心内容,通过实例和大量图表,结合实战,帮助学习者理解和运用,任何问题欢迎留言。 目录: zookeeper介绍与核心概念 安装和使用 ZooKeeper分布式锁实现 ZooKeeper框架Curator分布式锁实现及源代码分析 zookeeper 开发实战(java客户端) 上一篇文章中,我们使用zookeeper的java api实现了分布式排...

稀有气体的技术博客 6409

Curator 如何实现分布式锁

本文介绍了 Curator 框架中的 InterProcessMutex 具体是如何实现可重入的分布式排他锁,详细分析了加锁(acquire)和解锁(release)的核心流程:包括节点创建、锁竞争判断、前驱节点监听、锁计数管理等关键步骤,并对比了与原生Zookeeper实现相比的优势,如自动重连、Watcher管理、异常处理等。最后说明了通过异步方式处理节点变更事件来唤醒等待线程的机制

2301_76161469的博客 1188
上一篇: redission实现分布式锁(文字少,都是代码)
下一篇: centos集群上设置ssh免密登陆
livel_java
博客等级 码龄9年 2916粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值