spring集成redisson实现分布式锁

在单进程的系统中,当存在多个线程可以同时改变某个变量(可变共享变量)时,就需要对变量或代码块做同步,使其在修改这种变量时能够线性执行消除并发修改变量。

而Java提供的同步锁synchronized只能解决单台服务器上的并发问题,一般线上环境都是多台服务器部署同时运行,跨jvm的环境下synchronized的作用就不大了。这个时候redis就可以作为分布锁来使用了,一般都是基于redis setNx命令来实现自己的锁,建出来的键值一般都是有一个超时时间的(这个是Redis自带的超时特性),所以每个锁最终都会释放
这里介绍的是github上的一个开源项目,国外大神些的算法毕竟比自己实现的靠谱点

项目源码地址,里面不光有分布锁,还有分布锁队列等等一系列模块
https://github.com/redisson/redisson


pom.xml配置文件引人redisson相关包
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-all</artifactId>
    <version>2.10.5</version>
</dependency>

2. 配置方法
    2.1. 程序化配置方法
    Redisson程序化的配置方法是通过构建Config对象实例来实现的。例如:
    public class RedissonUtils {
        private static RedissonClient redissonClient;
        static{
            Config config = new Config();
            config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword(null);
            redissonClient = Redisson.create(config);
        }

        public static RedissonClient getRedisson(){
            return redissonClient;
        }


    public static void main(String[] args) throws InterruptedException{

        RLock fairLock = getRedisson().getLock("TEST_KEY");
        System.out.println(fairLock.toString());
//      fairLock.lock(); 
        // 尝试加锁,最多等待10秒,上锁以后10秒自动解锁
        boolean res = fairLock.tryLock(10, 10, TimeUnit.SECONDS);
        System.out.println(res);
        fairLock.unlock();

        //有界阻塞队列
//      RBoundedBlockingQueue<JSONObject> queue = getRedisson().getBoundedBlockingQueue("anyQueue");
        // 如果初始容量(边界)设定成功则返回`真(true)`,
        // 如果初始容量(边界)已近存在则返回`假(false)`。
//      System.out.println(queue.trySetCapacity(10));
//      JSONObject o=new JSONObject();
//      o.put("name", 1);
//      if(!queue.contains(o)){
//          queue.offer(o);
//      }

//      JSONObject o2=new JSONObject();
//      o2.put("name", 2);
        // 此时容量已满,下面代码将会被阻塞,直到有空闲为止。

//      if(!queue.contains(o2)){
//          queue.offer(o2);
//      }

//      //  获取但不移除此队列的头;如果此队列为空,则返回 null。
//      JSONObject obj = queue.peek();
//      //获取并移除此队列的头部,在指定的等待时间前等待可用的元素(如果有必要)。
//      JSONObject ob = queue.poll(10, TimeUnit.MINUTES);                                                    

        //获取并移除此队列的头,如果此队列为空,则返回 null。
//       Iterator<JSONObject> iterator=queue.iterator();
//       while (iterator.hasNext()){
//            JSONObject i =iterator.next();
//            System.out.println(i.toJSONString());
//            iterator.remove();
//          
//        }
//          while(queue.size()>0){
//              JSONObject ob = queue.poll();     
//              System.out.println(ob.toJSONString());
//          }
//      
//      JSONObject someObj = queue.poll();
//      System.out.println(someObj.toJSONString());
    }
2 spring集成的方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
     xmlns:redisson="http://redisson.org/schema/redisson" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://redisson.org/schema/redisson
                        http://redisson.org/schema/redisson/redisson.xsd">

    <context:component-scan base-package="component.controller.RedisServiceImpl" />

    <!-- redis连接池 -->  
    <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">          
        <property name="maxIdle" value="${redis_max_idle}"></property>   
        <property name="testOnBorrow" value="${redis_test_on_borrow}"></property>  
    </bean>  
    <!-- redis连接工厂 -->  
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
        <property name="hostName" value="${redis_addr}"></property>  
        <property name="port" value="${redis_port}"></property>  
        <property name="password" value="${redis_auth}"></property>  
        <property name="poolConfig" ref="jedisConfig"></property>  
    </bean>  
    <!-- redis操作模板,这里采用尽量面向对象的模板 -->  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory" ref="connectionFactory" />  
    <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->  
        <property name="keySerializer">  
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
        </property>  
        <property name="valueSerializer">  
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  
        </property>  
    </bean>     

    <!--redisson配置的实例    单台redis机器配置    -->
    <redisson:client id="redissonClient">
       <redisson:single-server address="redis://127.0.0.1:6379" connection-pool-size="30" />  
    </redisson:client>
</beans>

引入RedissonClient就可以使用了
@Autowired  
private RedissonClient redissonClient;

 //获取redissson分布式锁
 RLock fairLock = redissonClient.getLock("TEST_KEY");       
 //尝试加锁 最多等待100秒 20秒后自动销毁
boolean res = fairLock.tryLock(100, 20, TimeUnit.SECONDS);
 //释放锁
fairLock.unlock();

提醒:redis版本一定要3.0以上的 不然会报错,redis lua脚本

猜你喜欢

转载自blog.csdn.net/u010391342/article/details/78973582