redisson--分布式锁

本文详细介绍了如何在Java环境中使用Redisson实现分布式锁,包括依赖引入、配置客户端、创建线程池、具体应用实例以及编写Controller进行测试。通过具体代码示例展示了如何在多线程环境下正确使用Redisson的锁机制。
摘要由CSDN通过智能技术生成

1.依赖引入

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

2.获取RedisClient

package com.example.demo.lock;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LockDataConfig {
    @Bean
    public RedissonClient getClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://ip:port").setDatabase(15).setPassword("123456");
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
}

2.应用实例
2.1–体现锁机制此处利用ThreadPoolExecutor创建多线程方式调用

package com.example.demo.lock.executor;


import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池工具类
 */
public class ThreadExecutor {
    /**
		参数:核心线程数/最大线程数/空闲线程生存时间/生存时间单位/阻塞队列/拒绝策略
         * 拒绝策略:
         * (1)AbortPolicy
         ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
         (2)DiscardPolicy
         ThreadPoolExecutor.DiscardPolicy:丢弃任务,但是不抛出异常。如果线程队列已满,则后续提交				  的任务都会被丢弃,且是静默丢弃。
         使用此策略,可能会使我们无法发现系统的异常状态。建议是一些无关紧要的业务采用此策略。例如,本人的博客网站统计阅读量就是采用的这种拒绝策略。
         (3)DiscardOldestPolicy
         ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新提交被拒绝的任务。
         此拒绝策略,是一种喜新厌旧的拒绝策略。是否要采用此种拒绝策略,还得根据实际业务是否允许丢弃老任务来认真衡量。
         (4)CallerRunsPolicy
         ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务.如果任务被拒绝了,则由调用线程(提交任务的线程)直接执行此任务
*/
    public static ThreadPoolExecutor createExecutor() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("test-thread-pool-%d").build();
        
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
                16, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
        System.out.println("线程核心数" + Runtime.getRuntime().availableProcessors());
        return threadPoolExecutor;
    }
}

2.2具体应用实例

package com.example.demo.lock.service.impl;

import com.example.demo.lock.executor.ThreadExecutor;
import com.example.demo.lock.service.LockService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service("lockService")
public class LockServiceImpl implements LockService {
    @Autowired
    private RedissonClient redissonClient;
    int init = 1;
    int total = 100;

    /**
     * 加锁调用方法
     *
     * @param executor
     */
    private void printSthWithLock(ThreadPoolExecutor executor) {
        RLock mylock = redissonClient.getLock("mylock");
        while (true) {
            try {
                if (init > total) {
                    System.out.println(Thread.currentThread().getName() + "++++shutdown");
                    //线程停止
                    executor.shutdown();
                    executor.awaitTermination(0L, TimeUnit.SECONDS);
                    return;
                }
                boolean isLock = mylock.tryLock(500, 300, TimeUnit.MILLISECONDS);
                if (isLock) {
                    if (init <= total) {
                        //模拟网络阻塞
                        Thread.sleep(200);
                        System.out.println(Thread.currentThread().getName() + "++++" + init);
                        init++;
                    }
                }
            } catch (Exception e) {

            } finally {
                //释放锁
                mylock.unlock();
            }

        }

    }

    /**
     * 不加锁调用方法
     *
     * @param executor
     * @throws InterruptedException
     */
    private void printSthWithoutLock(ThreadPoolExecutor executor) throws InterruptedException {
        while (true) {
            if (init <= total) {
                System.out.println(Thread.currentThread().getName() + "++++++" + init);
                Thread.sleep(300);
                init++;
            } else {
                System.out.println("结束");
                executor.shutdown();
                executor.awaitTermination(0L, TimeUnit.SECONDS);
            }
        }
    }


    @Override
    public void exceutor() {
        ThreadPoolExecutor executor = ThreadExecutor.createExecutor();
        init = 1;
        //模拟多线程调用
        for (int i = 0; i < 200; i++) {
            executor.execute(() -> {
                try {
                    printSthWithLock(executor);
                } catch (Exception e) {

                }
            });
        }

    }
}

3.编写controller方便postMan测试

package com.example.demo.lock.controller;

import com.example.demo.lock.service.LockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/lock")
public class LockController {
    @Autowired
    private LockService lockService;

    @RequestMapping("/redisson")
    public String redissonLock() {
        lockService.exceutor();
        return "1";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值