Advertisement

Java常用代码块、工具类、常用框架、mysql常用语句模版汇总

阅读量:

Idea常用插件

  • Build Generator:生成builder模式的代码
  • MybatisX:mapper.xml文件和dao之间关联、映射
  • Lombok
  • Maven Helper:分析maven冲突等
  • Json parser

Java后台常用框架

  • springboot
  • springmvc
  • mybatis -plus
  • mysql
  • maven
  • junit
  • jackson
  • guava
  • apache commons utils
  • netty
  • swagger
  • joda-time

切面示例

定义注解

复制代码
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface DistributedLockAnnotation {
    
    String lockUniqueKey();
    
    int lockTime();
    
    TimeUnit lockTimeUnit();
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

定义切面

复制代码
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import java.lang.reflect.Method;
    
    // 切面定义
    @Aspect
    @Component
    public class DistributedLockAspect {
    
    @Autowired
    private DistributedLock distributedLock;
    
    // 切入点
    @Pointcut("@annotation(xx.xx.DistributedLockAnnotation)")
    public void logPointCut() {
    }
    
    // 环绕通知
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result;
        try {
            boolean locked = tryGetDistributeLock(point);
            if (!locked) {
                throw new RunTimeException("xx");
            }
            result = point.proceed();
        } catch (Throwable e) {
            throw e;
        }
        return result;
    }
    
    private boolean tryGetDistributeLock(ProceedingJoinPoint point) {
        try {
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            DistributedLock annotation = method.getAnnotation(DistributedLockAnnotation.class);
            String lockKey = SPELUtils.evalSPEl(point.getArgs(), method, annotation.uniqueKey());
            if (StringUtils.isBlank(lockKey)) {
                log.warn("xx, lockKey = " + lockKey);
                return false;
            }
            boolean locked = distributedLock.tryLock(lockKey, annotation.unit(), annotation.leaseTime());
            if (!locked) {
                log.warn("xx,, lockKey = " + lockKey + ", locked = " + locked);
            }
            return locked;
        } catch (Exception e) {
            log.error("", e);
        }
        return true;
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

常见java启动、停止、监控脚本

启动脚本

start.sh:

复制代码
    #!/bin/bash
    echo  "current path is : $(pwd)"
    source  /etc/profile
    
    # stop
    sh /xx/xx/stop.sh
    
    # 设置JAVA_HOME和CLASSPATH
    export JAVA_HOME=/xx/xx/java
    export BASE_DIR=/xx/xx/x
    
    # 设置服务名称
    SERVICE_NAME=your_service_namexx
    
    JAVA_OPTS="${JAVA_OPTS} -server -Xms4g -Xmx4g -Xmn2048m"
    JAVA_OPTS="${JAVA_OPTS} -XX:+UseG1GC -XX:G1HeapRegionSize=32m -XX:G1ReservePercent=25 -XX:InitiatingHeapOccupancyPercent=30 -XX:SoftRefLRUPolicyMSPerMB=0"
    JAVA_OPTS="${JAVA_OPTS} -verbose:gc -Xloggc:${BASE_PATH}/gclogs/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintAdaptiveSizePolicy"
    JAVA_OPTS="${JAVA_OPTS} -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=100m"
    JAVA_OPTS="${JAVA_OPTS} -XX:-OmitStackTraceInFastThrow"
    JAVA_OPTS="${JAVA_OPTS} -XX:+AlwaysPreTouch"
    JAVA_OPTS="${JAVA_OPTS} -XX:-UseLargePages -XX:-UseBiasedLocking"
    
    # 启动服务
    echo "start $SERVICE_NAME ..."
    nohup $JAVA_HOME/bin/java -jar $JAVA_OPTS -Dserver.port=xx /BASE_DIR/xx.jar > /dev/null 2>&1 &
    
    echo "Service $SERVICE_NAME is starting..."
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

停止脚本

stop.sh

复制代码
    #!/bin/bash
    
    # 设置JAVA_HOME和CLASSPATH
    export JAVA_HOME=/path/to/java
    export CLASSPATH=/path/to/classpath
    
    # 设置服务名称
    SERVICE_NAME=your_service_name
    
    # 停止服务
    PID=  ps -ef | grep $SERVICE_NAME | grep -v grep | awk '{print $2}'  
    if [ -n "$PID" ]; then
    kill $PID
    echo "Service $SERVICE_NAME is stopping..."
    else
    echo "Service $SERVICE_NAME is not running."
    fi
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

监控脚本

monitor.sh

复制代码
    #!/bin/bash
    
    # 设置JAVA_HOME和CLASSPATH
    export JAVA_HOME=/path/to/java
    export CLASSPATH=/path/to/classpath
    
    # 设置服务名称
    SERVICE_NAME=your_service_name
    
    # 检查服务是否运行
    PID=  ps -ef | grep $SERVICE_NAME | grep -v grep | awk '{print $2}'  
    if [ -n "$PID" ]; then
      echo "Service $SERVICE_NAME is running with PID $PID."
    else
      echo "Service $SERVICE_NAME is not running."
    fi
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

spel-eval

复制代码
    import org.springframework.core.DefaultParameterNameDiscoverer;
    import org.springframework.expression.EvaluationContext;
    import org.springframework.expression.Expression;
    import org.springframework.expression.spel.standard.SpelExpressionParser;
    import org.springframework.expression.spel.support.StandardEvaluationContext;
    
    import java.lang.reflect.Method;
    
    public static String evalSPEl(Object[] args, Method method, String spel) {
        DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(method);
        EvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < parameterNames.length; i++) {
            context.setVariable(parameterNames[i], args[i]);
        }
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(spel);
        Object result = expression.getValue(context);
        if (result == null) {
            return null;
        } else {
            return result.toString();
        }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读
复制代码
    @DistributedLock(lockUniqueKey = "'" + Constants.XX + "_" + "' + "
            + "#xx.xx1 + '_' + #xx.xx2.xx3",
            lockTimeUnit = TimeUnit.MILLISECONDS, lockTime = 1000)
    
    
      
      
      
    
    代码解读

线程池

线程池工具类

复制代码
    public class IdeThreadPools {
    // xx
    public static final ThreadPoolExecutor XX_POOL =
            initThreadPool(3, "XX_POOL", 500);
    
    private static ThreadPoolExecutor initThreadPool(int poolSize, String poolName, int workQueueSize) {
        ThreadPoolExecutor newExecutor = new ThreadPoolExecutor(poolSize, poolSize,
                0L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workQueueSize),
                new NamedTreadFactory(poolName), new DiscardLogPolicy());
        newExecutor.prestartAllCoreThreads();
        return newExecutor;
    }
    
    private static class NamedTreadFactory implements ThreadFactory {
    
        private final AtomicInteger threadNum = new AtomicInteger(1);
    
        private final String poolName;
    
        NamedTreadFactory(String poolName) {
            this.poolName = poolName;
        }
    
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, poolName + "-" + threadNum.getAndIncrement());
        }
    }
    
    private static class DiscardLogPolicy implements RejectedExecutionHandler {
    
        DiscardLogPolicy() {
        }
    
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("task执行被拒绝了, task = "
                    + r.toString() + ", pool = " + e.toString());
        }
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

异步执行工具类

复制代码
    public class AsyncUtils {
    
    public static void runAsync(Runnable runnable, Executor executor) {
        CompletableFuture.runAsync(runnable, executor);
    }
    }
    
    
      
      
      
      
      
      
    
    代码解读

数据库模型设计

基础字段

复制代码
    public class BaseTableModel {
    @TableId(type = IdType.AUTO)
    private Long id;
    
    private String createUserId;
    
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    
    private String updateUserId;
    
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

常用sql模版:common sql template

从其他表查询插入数据到目标表:insert into x select xx from xxx

复制代码
    insert into t_table1
    select c.x1,t.x2
    from
    t_t1 t, t_t2 c
    where
    t.id = c.x_id
    and ...;
    
    
      
      
      
      
      
      
      
    
    代码解读

更新表的某个字段为同记录的另外字段:update table column value use other column of same record

复制代码
    update t_x1 t set c1 = (select c1 from (
      select t.id, w.c1 from t_x1 t, t_x2 w 
      where t.id = w.tid
    ) inn where inn.id = t.id)
    
    
      
      
      
      
    
    代码解读
复制代码
    update t_xx a inner join t_xx b on a.id=b.id set a.time1 = b.time2
    
    
      
    
    代码解读
复制代码
    update t1 dst set field_xx = (
      select merge1.field_xx as field_xx from (
    select oldtd.field_xx1, oldtd.field_xx2, newtd.field_xx
    	  from t2 as newtd inner join t1 oldtd 
    	  on oldtd.field_xx2 = newtd.field_xx2
    	    and oldtd.field_xx1 = newtd.field_xx1
      ) merge1 where merge1.field_xx2 = dst.field_xx2 and merge1.field_xx1 = dst.field_xx1
     ) where field_xx1 in (select field_xx1 from t2)
    
    
    
      
      
      
      
      
      
      
      
      
    
    代码解读

增加索引:add index

复制代码
    alter table t_x1 add INDEX INDEX_NAME (`name`, `xx`);
    
    
      
    
    代码解读

建表模版

复制代码
    CREATE TABLE `t_xxxx` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
      ...
      `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
      `create_user_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '创建人id',
      `update_user_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '更新人id',
      PRIMARY KEY (`id`),
      UNIQUE KEY `UK_XX` (`xx1`, `xx2`),
      KEY `IDX_XX3` (`xx3`)
    ) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC COMMENT = 'xxdesc'
    
    
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

jackson

引入

复制代码
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
    </dependency>
    
    
      
      
      
      
      
    
    代码解读

代码块

复制代码
     private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
    static {
        OBJECT_MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    
    public static String toJson(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("xx", e);
        }
        return "";
    }
    
    public static <T> T toObj(String str, Class<T> cls) {
        try {
            return OBJECT_MAPPER.readValue(str, cls);
        } catch (Exception e) {
            log.error("xx", e);
        }
        return null;
    }
    
    public static <T> T toObj(String content, TypeReference<T> valueTypeRef) {
        try {
            return OBJECT_MAPPER.readValue(content, valueTypeRef);
        } catch (Exception e) {
            log.error("xx", e);
        }
        return null;
    }
    
    public static Map<String, Object> toMap(Object obj) {
        return toObj(toJson(obj), Map.class);
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

常用注解

字段名称转换

复制代码
    @JsonProperty("num_count")
    private Integer numCount;
    
    
      
      
    
    代码解读

时间格式化

复制代码
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;
    
    
      
      
      
    
    代码解读

序列化时忽略字段

复制代码
    @JsonIgnore
    private Boolean xx;
    
    
      
      
    
    代码解读

chrom插件

  • Google 翻译
  • AdGuard广告拦截器、AdBlock
  • Postman
  • FeHelper(网页常见开发工具,JSON格式化等)
  • Tampermonkey:脚本管理、扩展网页功能

Git

.gitignore文件不生效(.gitignore is not work)

git rm -r --cached .

拉取

  • git pull:拉取当前分支的最新代码
  • git pull origin master:拉取远端master代码到当前分支
  • git pull origin xx:拉取远端xx分支代码到当前分支

推送

  • git push:推送当前分支代码到远端同样分支

合并冲突

  • git merge --abort:合并中途撤销、还原合并

Git栈(本地,类似idea的Shelve)

  • git stash:隐藏变更
  • git stash pop:显示变更

推送新建分支与远端关联

git push --set-upstream origin xx-cur-branch-name

实用Idea的插件(useful idea plugins)

  • MybatisX

强制拉取最新JAR(force to refresh jars)

maven clean compile install -Dmaven.test.skip=true -U

困惑的小问题

String.trim不起作用

只能去掉英文下的半角空格\u0020,无法去除中文下的全角空格\u3000,可以先执行replaceAll(“\u00A0”," ")操作

数据模型开发管理平台

  • dbt labs
  • dataworks
  • dataphin
  • fiveran
  • dataform
  • prophecy
  • datameer
  • rivery

单测框架

junit
mockito
powermock
TestNG
EasyMock

Mockito

MockBean

mockbean定义的对象如xx的所有方法不会真实调用

复制代码
    @MockBean(org.springframework.boot.test.mock.mockito)
    private XX xx;
    
    
      
      
    
    代码解读

mock有返回值方法

复制代码
    @MockBean(org.springframework.boot.test.mock.mockito)
    private XX xx;
    
    Mockito.when(xx.aa()).thenReturn(..);
    
    
      
      
      
      
    
    代码解读

mock无返回值方法

复制代码
    org.mockito.Mockito.doNothing().when(xx).xxmethod();
    
    
      
    
    代码解读

设置成员变量的属性

复制代码
    org.springframework.test.util.ReflectionTestUtils.setField(xxInstance, "xxfield", "xxval");
    
    
      
    
    代码解读

mock抛出异常

复制代码
    when(xx.doxx(any(), any())).thenThrow(new XXException("xx"));
    
    
      
    
    代码解读

assert list相等

复制代码
    Assertions.assertIterableEquals(xx,xx)
    
    ### 常见模版引擎
    - Jinja2
    - freemarker
    - velocity
    
    
      
      
      
      
      
      
    
    代码解读

常用sql模版:common sql template

从其他表查询插入数据到目标表:insert into x select xx from xxx

复制代码
    insert into t_table1
    select c.x1,t.x2
    from
    t_t1 t, t_t2 c
    where
    t.id = c.x_id
    and ...;
    
    
      
      
      
      
      
      
      
    
    代码解读

更新表的某个字段为同记录的另外字段:update table column value use other column of same record

复制代码
    update t_x1 t set c1 = (select c1 from (
      select t.id, w.c1 from t_x1 t, t_x2 w 
      where t.id = w.tid
    ) inn where inn.id = t.id)
    
    
      
      
      
      
    
    代码解读
复制代码
    update t_xx a inner join t_xx b on a.id=b.id set a.time1 = b.time2
    
    
      
    
    代码解读
复制代码
    update t1 dst set field_xx = (
      select merge1.field_xx as field_xx from (
    select oldtd.field_xx1, oldtd.field_xx2, newtd.field_xx
    	  from t2 as newtd inner join t1 oldtd 
    	  on oldtd.field_xx2 = newtd.field_xx2
    	    and oldtd.field_xx1 = newtd.field_xx1
      ) merge1 where merge1.field_xx2 = dst.field_xx2 and merge1.field_xx1 = dst.field_xx1
     ) where field_xx1 in (select field_xx1 from t2)
    
    
    
      
      
      
      
      
      
      
      
      
    
    代码解读

增加索引:add index

复制代码
    alter table t_x1 add INDEX INDEX_NAME (`name`, `xx`);
    
    
      
    
    代码解读

建表模版

复制代码
    CREATE TABLE `t_xxxx` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
      ...
      `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
      `create_user_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '创建人id',
      `update_user_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '更新人id',
      PRIMARY KEY (`id`),
      UNIQUE KEY `UK_XX` (`xx1`, `xx2`),
      KEY `IDX_XX3` (`xx3`)
    ) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC COMMENT = 'xxdesc'
    
    
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

全部评论 (0)

还没有任何评论哟~