SpringBoot AOP @AfterThrowing+自定义注解+自定义异常使用

简介

利用SpringBoot AOP在程序抛出异常时执行对应的操作,在需要的方法上打上自定义的注解,在切面中进行配置。切面接收的参数就是就是抛出的异常,自定义异常存放数据。(适合抛出异常后要进行操作的情况)

自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SyncData {
}

自定义异常

public class SyncDataException extends RuntimeException{

	/**
	 * 失败的impl实现类
	 */
	private SynChroBean synChroBean;
	/**
	 * 失败时第几次的循环
	 */
	private int index;
	/**
	 * 每页数量
	 */
	private int pageSize;

	/**
	 * 总页数
	 */
	private int totalPage;

	public SyncDataException(String message,SynChroBean synChroBean,int index,int totalPage,int pageSize) {
		super(message);
		this.synChroBean = synChroBean;
		this.index = index;
		this.pageSize = pageSize;
		this.totalPage = totalPage;
	}

	public SynChroBean getSynChroBean() {
		return synChroBean;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public int getIndex() {
		return index;
	}

	public int getPageSize() {
		return pageSize;
	}
}

切面类

@Aspect
@Component
public class SyncDataAspect {


	@Autowired
	private DynamicThirdDataSourceService dynamicThirdDataSourceService;


	@AfterThrowing(throwing="ex",pointcut="@annotation(SyncData)")
	public void doRecoveryActions(SyncDataException ex){

		//在这里重试调用
		SyncDataException syncDataException = ex;
		int index = syncDataException.getIndex();
		SynChroBean synChroBean = syncDataException.getSynChroBean();
		int pageSize = syncDataException.getPageSize();
		int totalPage = syncDataException.getTotalPage();
		dynamicThirdDataSourceService.synchroData(synChroBean,index,totalPage,pageSize);
	}

}

使用

@SyncData  //配置自定义注解
	public void synchroData(SynChroBean synChroBean,int index,int totalPage,int pageSize) {
		//找到对应的ServiceImpl class
		Class serviceImplClass = synChroBean.getClazz();
		//获取bean容器中配置类Mapper的实例
		Object ThirdDataSourceMapper = context.getBean(DynamicThirdDataSourceMapper.class);
		//获取bean容器中ServiceImpl的实例
		TableOperateMethod tableOperateMethod = (TableOperateMethod) context.getBean(serviceImplClass);
		int j = 0;
		try {
			for (int i = index; i <= totalPage; i++) {
				j = i;
				//查询出第三方表的数据List
				List dataList = (List) synChroBean.getMethod().invoke(ThirdDataSourceMapper, pageSize, i*pageSize);
				tableOperateMethod.execute(dataList,false);
			}
			//同步后删除旧数据
			tableOperateMethod.deleteOldData();
		} catch (Exception e) {
			try {
				Thread.sleep(10000);
			} catch (InterruptedException interruptedException) {
				interruptedException.printStackTrace();
			}
			//抛出自定义异常,被切面捕获
			throw new SyncDataException(e.getMessage(),synChroBean,j,totalPage,pageSize);
		}
	}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Redisson 实现分布式锁,具体实现如下: 1. 引入 Redisson 依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.1</version> </dependency> ``` 2. 定义自定义注解 `DistributedLock`: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DistributedLock { String value() default ""; long leaseTime() default 30L; TimeUnit timeUnit() default TimeUnit.SECONDS; } ``` 3. 在需要加锁的方法上加上 `@DistributedLock` 注解: ```java @Service public class UserService { @DistributedLock("user:#{#userId}") public User getUserById(String userId) { // ... } } ``` 4. 实现 `DistributedLockAspect` 切面: ```java @Aspect @Component public class DistributedLockAspect { private final RedissonClient redissonClient; public DistributedLockAspect(RedissonClient redissonClient) { this.redissonClient = redissonClient; } @Around("@annotation(distributedLock)") public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable { String lockKey = distributedLock.value(); if (StringUtils.isEmpty(lockKey)) { lockKey = joinPoint.getSignature().toLongString(); } RLock lock = redissonClient.getLock(lockKey); boolean locked = lock.tryLock(distributedLock.leaseTime(), distributedLock.timeUnit()); if (!locked) { throw new RuntimeException("获取分布式锁失败"); } try { return joinPoint.proceed(); } finally { lock.unlock(); } } } ``` 5. 在 `application.yml` 中配置 Redisson: ```yaml spring: redis: host: localhost port: 6379 password: database: 0 redisson: single-server-config: address: redis://${spring.redis.host}:${spring.redis.port} ``` 这样就实现了一个基于 Redis 的分布式锁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值