当前位置: 首页 > news >正文

2024-01-开发技术积累

文章目录

  • 递归删除文件
  • 执行任务超时时间
  • 读写锁
  • 获取异常栈信息
  • 通过NIO读取文件
  • 单例模式代码
  • NIO管道写文件(来自nacos)
  • NIO读取文件(来自Nacos)
  • spring指定注解扫描

递归删除文件

xxl-job源码

   public static boolean deleteRecursively(File root) {if (root != null && root.exists()) {if (root.isDirectory()) {File[] children = root.listFiles();if (children != null) {for (File child : children) {deleteRecursively(child);}}}return root.delete();}return false;}

执行任务超时时间

xxl-job源码

	if (triggerParam.getExecutorTimeout() > 0) {// limit timeoutThread futureThread = null;try {//创建一个执行任务线程FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new Callable<Boolean>() {@Overridepublic Boolean call() throws Exception {// init job contextXxlJobContext.setXxlJobContext(xxlJobContext);handler.execute();return true;}});futureThread = new Thread(futureTask);futureThread.start();//通过线程的超时机制,来实现任务超时Boolean tempResult = futureTask.get(triggerParam.getExecutorTimeout(), TimeUnit.SECONDS);} 

读写锁

ReentrantReadWriteLock

以下代码 来自官方文档

class RWDictionary {private final Map<String, Data> m = new TreeMap<String, Data>();private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();private final Lock r = rwl.readLock();private final Lock w = rwl.writeLock();public Data get(String key) {r.lock();try { return m.get(key); }finally { r.unlock(); }}public String[] allKeys() {r.lock();try { return m.keySet().toArray(); }finally { r.unlock(); }}public Data put(String key, Data value) {w.lock();try { return m.put(key, value); }finally { w.unlock(); }}public void clear() {w.lock();try { m.clear(); }finally { w.unlock(); }}}

获取异常栈信息

StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
String errorMsg = stringWriter.toString();

通过NIO读取文件

nacos源码中,如果是多实例,就采用nio读取文件

 public static String getFileContent(File file, String charsetName) throws IOException {RandomAccessFile fis = null;FileLock rlock = null;try {fis = new RandomAccessFile(file, "r");FileChannel fcin = fis.getChannel();int i = 0;do {try {rlock = fcin.tryLock(0L, Long.MAX_VALUE, true);} catch (Exception e) {++i;if (i > RETRY_COUNT) {LOGGER.error("read {} fail;retryed time:{}", file.getName(), i);throw new IOException("read " + file.getAbsolutePath() + " conflict");}sleep(SLEEP_BASETIME * i);LOGGER.warn("read {} conflict;retry time:{}", file.getName(), i);}} while (null == rlock);int fileSize = (int) fcin.size();ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);fcin.read(byteBuffer);byteBuffer.flip();return byteBufferToString(byteBuffer, charsetName);} finally {if (rlock != null) {rlock.release();rlock = null;}if (fis != null) {fis.close();fis = null;}}}public static String byteBufferToString(ByteBuffer buffer, String charsetName) throws IOException {Charset charset = null;CharsetDecoder decoder = null;CharBuffer charBuffer = null;charset = Charset.forName(charsetName);decoder = charset.newDecoder();charBuffer = decoder.decode(buffer.asReadOnlyBuffer());return charBuffer.toString();}

单例模式代码

public final class GlobalAdvisorAdapterRegistry {private GlobalAdvisorAdapterRegistry() {}/*** Keep track of a single instance so we can return it to classes that request it.*/private static AdvisorAdapterRegistry instance = new DefaultAdvisorAdapterRegistry();/*** Return the singleton {@link DefaultAdvisorAdapterRegistry} instance.*/public static AdvisorAdapterRegistry getInstance() {return instance;}/*** Reset the singleton {@link DefaultAdvisorAdapterRegistry}, removing any* {@link AdvisorAdapterRegistry#registerAdvisorAdapter(AdvisorAdapter) registered}* adapters.*/static void reset() {instance = new DefaultAdvisorAdapterRegistry();}}

NIO管道写文件(来自nacos)

nacos raft协议 写文件

ByteBuffer data;//通过nio  管道写文件data = ByteBuffer.wrap(JacksonUtils.toJson(datum).getBytes(StandardCharsets.UTF_8));try (FileChannel fc = new FileOutputStream(cacheFile, false).getChannel()) {fc.write(data, data.position());fc.force(true);} catch (Exception e) {MetricsMonitor.getDiskException().increment();throw e;}

NIO读取文件(来自Nacos)

数据恢复,从文件中加载数据

        ByteBuffer buffer;try (FileChannel fc = new FileInputStream(file).getChannel()) {//申请内存空间buffer = ByteBuffer.allocate((int) file.length());//读数据到bufferfc.read(buffer);String json = new String(buffer.array(), StandardCharsets.UTF_8);if (StringUtils.isBlank(json)) {return null;}}

spring指定注解扫描

 ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);if (this.resourceLoader != null) {scanner.setResourceLoader(this.resourceLoader);}//只扫描Mapper.class注解scanner.setAnnotationClass(Mapper.class);scanner.registerFilters();scanner.doScan(StringUtils.toStringArray(packages));

请添加图片描述


http://www.mrgr.cn/news/5330.html

相关文章:

  • 攻防世界-web题型-2星难度汇总-个人wp
  • MTK 5G旗舰智能手机SoC芯片——MT6989(天玑9300)
  • 排序之插入排序
  • 远程服务器文件和本地文件同步的一个方法
  • pytorch 快速入门-方法篇
  • [LeetCode]438.找到字符串中所有字母异位词(C++)
  • 32次8.21(学习playbook-roles,脚本创建数据库和表,mycat读写分离)
  • 教你一键快速生成词云图片
  • 双向通信之Websocket
  • LeetCode 算法:划分字母区间 c++
  • MySQL: find_in_set基本使用
  • 发布MindSearch到ModelScope创空间
  • 线程的锁机制
  • 利用puppeteer将html网页生成图片
  • 网络编程
  • Neo4j 图数据库入门
  • Java爬虫图像处理:从获取到解析
  • 深入探索【Hadoop】生态系统:Hive、Pig、HBase及更多关键组件(上)
  • CSS3-新特性
  • 2024年如何将低质量视频变成高质量视频