重庆黔江做防溺水的网站,东莞网络营销班,成都百度seo公司,公司网站是用什么软件做文章目录 前言一、Redission是什么#xff1f;二、使用场景三、代码实战1.项目结构2.类图3.maven依赖4.yml5.config6.annotation7.aop8.model9.service 四、单元测试总结 前言
在集群环境下非单体应用存在的问题#xff1a;JVM锁只能控制本地资源的访问#xff0c;无法控制… 文章目录 前言一、Redission是什么二、使用场景三、代码实战1.项目结构2.类图3.maven依赖4.yml5.config6.annotation7.aop8.model9.service 四、单元测试总结 前言
在集群环境下非单体应用存在的问题JVM锁只能控制本地资源的访问无法控制多个JVM间的资源访问所以需要借助第三方中间件来控制整体的资源访问redis是一个可以实现分布式锁保证AP的中间件可以采用setnx命令进行实现但是在实现细节上也有很多需要注意的点比如说获取锁、释放锁时机、锁续命问题而redission工具能够有效降低实现分布式锁的复杂度看门狗机制有效解决锁续命问题。 一、Redission是什么
Redisson是一个用于Java的Redis客户端它提供了许多分布式对象和服务使得在Java应用中使用Redis变得更加便捷。Redisson提供了对Redis的完整支持并附带了一系列的功能如分布式锁、分布式集合、分布式对象、分布式队列等。 二、使用场景
分布式锁Redisson提供了强大的分布式锁机制通过基于Redis的分布式锁可以保证在分布式环境下的数据一致性。常见的使用场景包括分布式任务调度、防止重复操作、资源竞争控制等。分布式集合Redisson提供了一系列的分布式集合实现如Set、List、Queue、Deque等。这些集合的特点是数据分布在多台机器上并且支持并发访问适用于需要在多个节点之间共享数据的场景。分布式对象Redisson支持将普通Java对象转换为可在Redis中存储和操作的分布式对象。这些对象可以跨JVM进行传输并保持一致性。使用分布式对象可以方便地实现分布式缓存、会话管理等功能。分布式队列Redisson提供了高级的分布式队列实现支持公平锁和非公平锁的排队方式。分布式队列可以在多个线程和多个JVM之间进行数据传输适用于消息队列、异步任务处理等场景。分布式信号量、锁定和闭锁Redisson提供了分布式信号量、可重入锁和闭锁等机制用于实现更复杂的并发控制需求。这些工具能够有效地管理并发访问确保在分布式环境下的数据操作的正确性。
除了以上提到的功能Redisson还提供了许多其他的分布式应用场景所需的功能组件如分布式BitSet、分布式地理位置、分布式发布/订阅等。 三、代码实战
通过aop切面编程可以降低与业务代码的耦合度便于拓展和维护
1.项目结构 2.类图 3.maven依赖
dependencies!-- Spring Boot --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependency!-- Redisson --dependencygroupIdorg.redisson/groupIdartifactIdredisson/artifactIdversion3.20.0/version/dependency!-- Spring AOP --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId/dependency!-- Spring Expression Language (SpEL) --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactIdoptionaltrue/optional/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactId/dependency
/dependencies4.yml
dserver:port: 8081spring:redis:host: localhostport: 6379# 如果需要密码认证请使用以下配置# password: your_password5.config
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** author 28382*/
Configuration
public class RedissonConfig {Value(${spring.redis.host})private String redisHost;Value(${spring.redis.port})private int redisPort;// 如果有密码认证请添加以下注解并修改相应的配置//Value(${spring.redis.password})//private String redisPassword;Bean(destroyMethod shutdown)public RedissonClient redissonClient() {Config config new Config();config.useSingleServer().setAddress(redis:// redisHost : redisPort);// 如果有密码认证请添加以下配置//config.useSingleServer().setPassword(redisPassword);return Redisson.create(config);}
}import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** author 28382*/
Configuration
public class RedisTemplateConfig {Beanpublic RedisTemplateString, Object redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplateString, Object template new RedisTemplate();template.setConnectionFactory(connectionFactory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());template.afterPropertiesSet();return template;}
}6.annotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** author 28382*/
Target(ElementType.METHOD)
Retention(RetentionPolicy.RUNTIME)
public interface DistributedLock {// 自定义业务keysString[] keys() default {};// 租赁时间 单位毫秒long leaseTime() default 30000;// 等待时间 单位毫秒long waitTime() default 3000;}7.aop
支持解析 SpEL
import com.mxf.code.annotation.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;Aspect
Component
Slf4j
public class DistributedLockAspect {Autowiredprivate RedissonClient redissonClient;Around(annotation(distributedLock))public Object lockMethod(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {MethodSignature methodSignature (MethodSignature) joinPoint.getSignature();Method method methodSignature.getMethod();// 获取自定义业务keysString[] keys distributedLock.keys();// 租赁时间long leaseTime distributedLock.leaseTime();// 等待时间long waitTime distributedLock.waitTime();// 创建参数名发现器ParameterNameDiscoverer parameterNameDiscoverer new DefaultParameterNameDiscoverer();// 获取方法参数名String[] parameterNames parameterNameDiscoverer.getParameterNames(method);// 创建 SpEL 解析器ExpressionParser expressionParser new SpelExpressionParser();// 创建 SpEL 上下文EvaluationContext evaluationContext new StandardEvaluationContext();// 设置方法参数值到 SpEL 上下文中Object[] args joinPoint.getArgs();if (parameterNames ! null args ! null parameterNames.length args.length) {for (int i 0; i parameterNames.length; i) {evaluationContext.setVariable(parameterNames[i], args[i]);}}// 构建完整的锁键名StringBuilder lockKeyBuilder new StringBuilder();if (keys.length 0) {for (String key : keys) {if (StringUtils.hasText(key)) {try {// 解析 SpEL 表达式获取属性值Object value expressionParser.parseExpression(key).getValue(evaluationContext);lockKeyBuilder.append(value).append(:);} catch (SpelEvaluationException ex) {// 如果解析失败则使用原始字符串作为属性值LiteralExpression expression new LiteralExpression(key);lockKeyBuilder.append(expression.getValue()).append(:);}}}}// 使用方法名作为最后一部分键名lockKeyBuilder.append(methodSignature.getName());String fullLockKey lockKeyBuilder.toString();// 获取 Redisson 锁对象RLock lock redissonClient.getLock(fullLockKey);// 尝试获取分布式锁// boolean tryLock(long waitTime, long leaseTime, TimeUnit unit)boolean success lock.tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);if (success) {try {// 执行被拦截的方法return joinPoint.proceed();} finally {// 释放锁lock.unlock();}} else {log.error(Failed to acquire distributed lock);// 获取锁超时抛出异常throw new RuntimeException(Failed to acquire distributed lock);}}}8.model import lombok.Data;/*** author 28382*/
Data
public class User {private Long id;private String name;private String address;public User(Long id, String name) {this.id id;this.name name;}
}9.service
import com.mxf.code.annotation.DistributedLock;
import com.mxf.code.model.User;
import org.springframework.stereotype.Service;/*** author 28382*/
Service
public class UserService {int i 0;DistributedLockpublic void test01() {System.out.println(执行方法1 , 当前线程: Thread.currentThread().getName() 执行的结果是 i);sleep();}DistributedLock(keys myKey,leaseTime 30L)public void test02() {System.out.println(执行方法2 , 当前线程: Thread.currentThread().getName() 执行的结果是 i);sleep();}DistributedLock(keys #user.id)public User test03(User user) {System.out.println(执行方法3 , 当前线程: Thread.currentThread().getName() 执行的结果是 i);sleep();return user;}DistributedLock(keys {#user.id, #user.name}, leaseTime 5000, waitTime 5000)public User test04(User user) {System.out.println(执行方法4 , 当前线程: Thread.currentThread().getName() 执行的结果是 i);sleep();return user;}private void sleep() {// 模拟业务耗时try {Thread.sleep(1000L);} catch (InterruptedException e) {throw new RuntimeException(e);}}}四、单元测试
import com.mxf.code.model.User;
import com.mxf.code.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;SpringBootTest(classes SpringBootLockTest.class)
SpringBootApplication
public class SpringBootLockTest {AutowiredUserService userService;private static final Random RANDOM new Random();public static void main(String[] args) {SpringApplication.run(SpringBootLockTest.class, args);}Testpublic void test01() throws Exception {ExecutorService executorService Executors.newFixedThreadPool(10);Runnable task () - userService.test01();for (int i 0; i 100; i) {executorService.submit(task);}Thread.sleep(10000);}Testpublic void test02() throws Exception {ExecutorService executorService Executors.newFixedThreadPool(10);Runnable task () - userService.test02();for (int i 0; i 100; i) {executorService.submit(task);}Thread.sleep(10000L);}Testpublic void test03() throws Exception {ExecutorService executorService Executors.newFixedThreadPool(10);Runnable task () - userService.test03(new User(1L, name));for (int i 0; i 100; i) {executorService.submit(task);}Thread.sleep(10000L);}Testpublic void test04() throws Exception {ExecutorService executorService Executors.newFixedThreadPool(10);Runnable task () - userService.test04(new User(1L, name));for (int i 0; i 100; i) {executorService.submit(task);}Thread.sleep(100000L);}
}test01 test02 test03 test04 总结
可以在项目中单独建立一个Module需要的子系统直接引入在需要加分布式的业务代码方法上添加注解及配注解属性值即可存在一个潜在的问题就是如果redis使用主从架构在主节点和从节点同步加锁信息时主节点挂掉这时选取一个暂未同步完整节点信息的从节点作为主节点时存在一定锁失效的问题这是可以考虑红锁或者zookeeper实现强一致性。 文章转载自: http://www.morning.zwdrz.cn.gov.cn.zwdrz.cn http://www.morning.gbsfs.com.gov.cn.gbsfs.com http://www.morning.gthwz.cn.gov.cn.gthwz.cn http://www.morning.htsrm.cn.gov.cn.htsrm.cn http://www.morning.mnwsy.cn.gov.cn.mnwsy.cn http://www.morning.mtsck.cn.gov.cn.mtsck.cn http://www.morning.zmwzg.cn.gov.cn.zmwzg.cn http://www.morning.ymmjx.cn.gov.cn.ymmjx.cn http://www.morning.qhjkz.cn.gov.cn.qhjkz.cn http://www.morning.kxqfz.cn.gov.cn.kxqfz.cn http://www.morning.playmi.cn.gov.cn.playmi.cn http://www.morning.sgfgz.cn.gov.cn.sgfgz.cn http://www.morning.yesidu.com.gov.cn.yesidu.com http://www.morning.bkppb.cn.gov.cn.bkppb.cn http://www.morning.npmcf.cn.gov.cn.npmcf.cn http://www.morning.spbp.cn.gov.cn.spbp.cn http://www.morning.eviap.com.gov.cn.eviap.com http://www.morning.jkfyt.cn.gov.cn.jkfyt.cn http://www.morning.cpmwg.cn.gov.cn.cpmwg.cn http://www.morning.mpszk.cn.gov.cn.mpszk.cn http://www.morning.yrhpg.cn.gov.cn.yrhpg.cn http://www.morning.mzkn.cn.gov.cn.mzkn.cn http://www.morning.fbrshjf.com.gov.cn.fbrshjf.com http://www.morning.lhzqn.cn.gov.cn.lhzqn.cn http://www.morning.stprd.cn.gov.cn.stprd.cn http://www.morning.cprbp.cn.gov.cn.cprbp.cn http://www.morning.ghfmd.cn.gov.cn.ghfmd.cn http://www.morning.lsqxh.cn.gov.cn.lsqxh.cn http://www.morning.qdrrh.cn.gov.cn.qdrrh.cn http://www.morning.hympq.cn.gov.cn.hympq.cn http://www.morning.sgmgz.cn.gov.cn.sgmgz.cn http://www.morning.shnqh.cn.gov.cn.shnqh.cn http://www.morning.coatingonline.com.cn.gov.cn.coatingonline.com.cn http://www.morning.ssfq.cn.gov.cn.ssfq.cn http://www.morning.mlnbd.cn.gov.cn.mlnbd.cn http://www.morning.wqbrg.cn.gov.cn.wqbrg.cn http://www.morning.smdkk.cn.gov.cn.smdkk.cn http://www.morning.rfrxt.cn.gov.cn.rfrxt.cn http://www.morning.czwed.com.gov.cn.czwed.com http://www.morning.drkk.cn.gov.cn.drkk.cn http://www.morning.sskns.cn.gov.cn.sskns.cn http://www.morning.rjljb.cn.gov.cn.rjljb.cn http://www.morning.dbtdy.cn.gov.cn.dbtdy.cn http://www.morning.jthjr.cn.gov.cn.jthjr.cn http://www.morning.jtkfm.cn.gov.cn.jtkfm.cn http://www.morning.rqkk.cn.gov.cn.rqkk.cn http://www.morning.gkktj.cn.gov.cn.gkktj.cn http://www.morning.srgbr.cn.gov.cn.srgbr.cn http://www.morning.bbrf.cn.gov.cn.bbrf.cn http://www.morning.clkjn.cn.gov.cn.clkjn.cn http://www.morning.lztrt.cn.gov.cn.lztrt.cn http://www.morning.dbjyb.cn.gov.cn.dbjyb.cn http://www.morning.xpqsk.cn.gov.cn.xpqsk.cn http://www.morning.bkppb.cn.gov.cn.bkppb.cn http://www.morning.kqwsy.cn.gov.cn.kqwsy.cn http://www.morning.rrxnz.cn.gov.cn.rrxnz.cn http://www.morning.pjfmq.cn.gov.cn.pjfmq.cn http://www.morning.xkyqq.cn.gov.cn.xkyqq.cn http://www.morning.dblgm.cn.gov.cn.dblgm.cn http://www.morning.spfq.cn.gov.cn.spfq.cn http://www.morning.rmmz.cn.gov.cn.rmmz.cn http://www.morning.gzxnj.cn.gov.cn.gzxnj.cn http://www.morning.jhswp.cn.gov.cn.jhswp.cn http://www.morning.wyrkp.cn.gov.cn.wyrkp.cn http://www.morning.hcsqznn.cn.gov.cn.hcsqznn.cn http://www.morning.nlffl.cn.gov.cn.nlffl.cn http://www.morning.cwkcq.cn.gov.cn.cwkcq.cn http://www.morning.rpgdd.cn.gov.cn.rpgdd.cn http://www.morning.ftsmg.com.gov.cn.ftsmg.com http://www.morning.xhfky.cn.gov.cn.xhfky.cn http://www.morning.bmsqq.cn.gov.cn.bmsqq.cn http://www.morning.bpmnj.cn.gov.cn.bpmnj.cn http://www.morning.lrybz.cn.gov.cn.lrybz.cn http://www.morning.bsrp.cn.gov.cn.bsrp.cn http://www.morning.kltmt.cn.gov.cn.kltmt.cn http://www.morning.rmtmk.cn.gov.cn.rmtmk.cn http://www.morning.yrnll.cn.gov.cn.yrnll.cn http://www.morning.ktmnq.cn.gov.cn.ktmnq.cn http://www.morning.qrmry.cn.gov.cn.qrmry.cn http://www.morning.ryysc.cn.gov.cn.ryysc.cn