zoukankan      html  css  js  c++  java
  • 分布式锁-----秒杀系统

    1.ZK

    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;
    
    public class TestZK {
    	//定义共享资源
    	private static int NUMBER = 10;
    	private static void getNumber(){
    		System.out.println("*********业务方法开始*********");
    		System.out.println("当前值:"+NUMBER);
    		NUMBER--;
    		
    		try {
    			Thread.sleep(2000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		System.out.println("*********业务方法结束*********");
    	}
    
    	public static void main(String[] args) {
    		//定义retrypolicy 重试策略
    		RetryPolicy policy = new ExponentialBackoffRetry(1000,   //等待的时间
    				                                         10);//重试的测试
    		
    		//定义ZK的客户端
    		CuratorFramework client = CuratorFrameworkFactory.builder()
    				                  .connectString("192.168.56.111:2181")
    				                  .retryPolicy(policy)
    				                  .build();
    		client.start();
    		
    		//定义锁
    		final InterProcessMutex lock = new InterProcessMutex(client,"/mylock");
    				
    		for(int i=0;i<10;i++){
    			new Thread(new Runnable() {
    				
    				public void run() {
    					
    					try {
    						//请求锁
    						lock.acquire();
    						
    						// 访问业务方法
    						getNumber();						
    					} catch (Exception e) {
    						e.printStackTrace();
    					}finally{
    						try {
    							lock.release();
    						} catch (Exception e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    
    				}
    			}).start();
    		}
    
    	}
    }
    

    2.Redis

  • 相关阅读:
    Linux安全加固
    mosquitto
    Docker设置2375端口
    linux shell 常见的时间戳操作
    tar打包并且排除log目录
    spring boot2整合shiro安全框架实现前后端分离的JWT token登录验证
    http post
    scp命令 Linux和Windows文件互传
    git did not exit cleanly (exit code 1) 的解决办法
    windows安装TortoiseGit详细使用教程【基础篇】
  • 原文地址:https://www.cnblogs.com/zgzf/p/10418655.html
Copyright © 2011-2022 走看看