常用工具积累java(持续更新)

1.ListToMap 将用户集合中的每个用户的id和username放到map中
Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername));

Map<Integer, TrainNumberDetail> trainNumberDetailMap = trainNumberDetailListRestRes.getResult ().stream ().collect (Collectors.toMap (TrainNumberDetail::getId, Function.identity()));

2.用separator分割value 例如separator="," value="he,we,she"
Iterable<String> res = Splitter.on(separator).trimResults().omitEmptyStrings().split(value);
    @Test
    public void testSplit_On_Split_OmitEmpty() {
        List<String> result = Splitter.on("|").splitToList("hello|world|||");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(5));

        result = Splitter.on("|").omitEmptyStrings().splitToList("hello|world|||");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(2));
    }
	
	List<String> result = Splitter.fixedLength(4).splitToList("aaaabbbbccccdddd");
	
	List<String> result = Splitter.on("#").limit(3).splitToList("hello#world#java#google#scala");
	
	
3. 添加@JsonIgnore在方法或者字段上不参与json序列化


4.批量修改
<update id="updateThreadreturnList"  parameterType="java.util.List">  
	update tb_thread set isDelete=0
	where threadId in ( 
		<foreach collection="list" item="item" index="index" open="" close="" separator=",">
			#{item.threadId}
		</foreach>      
	)     
</update>
注意 需要在数据库添加 &allowMultiQueries=true 
jdbc:mysql://192.168.1.109:3306/healthmanage?characterEncoding=utf-8&allowMultiQueries=true
 
<update id="updateQuestionseleteTempalteList"  parameterType="java.util.List">  
	<foreach collection="list" item="item" index="index">
		update tb_question_template_seleteitem_detail set selectedName=#{item.selectedName}
		where 1=1 and  selectedId =#{item.selectedId  };
	</foreach>      
</update>

5.批量插入
(1)replace into 替换数据库记录,需要表中有主键或者unique索引,如果数据库已存在的数据,会先删除该数据然后新增。不存在的数据效果和insert into 一样。
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="id">
    replace into GOVRECEIPTS (state,orgname,orgaddr,regauth,rcptyear,receipts,crtdate)
    values
	<foreach collection="list" item="item" index="index" separator=",">
	  (#{item.state}, #{item.orgname}, #{item.orgaddr}, #{item.regauth},
	  #{item.rcptyear}, #{item.receipts}, #{item.crtdate})
	</foreach>
</insert>
(2)insert ignore 需要表中有主键或者unique索引,如果数据库中存在相同的数据,则忽略当前数据。不存在的数据效果和insert into 一样。
<insert id="insertInfoBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
    insert ignore GOVRECEIPTS (state,orgname,orgaddr,regauth,rcptyear,receipts,crtdate)
    values
    <foreach collection="list" item="item" index="index" separator=",">
      (#{item.state}, #{item.orgname}, #{item.orgaddr}, #{item.regauth},
      #{item.rcptyear}, #{item.receipts}, #{item.crtdate})
</foreach>
(3)insert的时候判断是否存在
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="id">
	     insert into test (id, username) 
	    <foreach collection="list" index="index" item="item" separator="union all">  	
	     ( 
	      select 
	      #{item.id,jdbcType=BIGINT}, #{item.username,jdbcType=VARCHAR} 
	      from dual where not exists(
	      	select id,username from test where id = #{item.id,jdbcType=BIGINT} and username = #{item.username,jdbcType=VARCHAR} 
	      )
      	 )
		</foreach>
</insert>

6.
<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.11</version>
</dependency>
Md5加密举例:DigestUtils.md5Hex("000000");
String random = RandomStringUtils.random(5);//𠡠尐𞸎
System.out.println(random);
random = RandomStringUtils.randomAlphabetic(5);//NYMdk
System.out.println(random);
random = RandomStringUtils.randomNumeric(5);//15116
System.out.println(random);
random = RandomStringUtils.randomAlphanumeric(5);//6IKLj
System.out.println(random);
random = RandomStringUtils.randomAscii(5);//"6$&w
System.out.println(random);

Math.ceil(1.01)->2

nohup java -jar spider-1.0.0.jar >/dev/null 2>&1 &

div.taxBox#taxBox>(ul>li*3)+(div*3)
ul>li*3>a[href="#"]

mvn clean package -Dmaven.test.skip=true -U
cd target
java -jar xx.jar --spring.profiles.active=server1

npm install http-server -g
hs -o -p 8888

StringUtils.substringBeforeLast(str.toString(), ".");删除指定符号之后所有的字符

5.统一json时间格式返回
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
6.异常处理
public class ExceptionUtil {
	public static String getMessage(Exception e) {
		StringWriter sw = null;
		PrintWriter pw = null;
		try {
			sw = new StringWriter();
			pw = new PrintWriter(sw);
			// 将出错的栈信息输出到printWriter中
			e.printStackTrace(pw);
			pw.flush();
			sw.flush();
		} finally {
			if (sw != null) {
				try {
					sw.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (pw != null) {
				pw.close();
			}
		}
		return sw.toString();
	}
}
log.error(ExceptionUtil.getMessage(e));

7.获取request
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes)requestAttributes;
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("X-Token");

8.后端传递token
(1)RestTemplate传递(exchange()方法或者ClientRequestInterceptor接口)
①interceptor
②restTemplate注入的时候加入拦截器
String token = request.getHeader("X-Token");
headers.add("X-Token", token);

&serverTimezone=GMT%2B8

9.nginx pid打不开:
	①没有目录则创建。
	②指定配置文件启动nginx -c /nginx.conf & nginx -s reload

@EnableDiscoveryClient
@SpringBootApplication
@EnableDubboConfig
@MapperScan("mapper")
public class ProducerApplication {

    public static void main(String[] args) {
        SpringApplication.run (ProducerApplication.class, args);
        Runtime.getRuntime ().addShutdownHook (new Thread (new Runnable () {
            @Override
            public void run() {
                System.out.println ("执行JVM shutdown");
            }
        }));
    }
}

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareServiceImpl implements ShareService {
    private final ShareMapper shareMapper;
    private final RocketMQTemplate rocketMQTemplate;
}

@RunWith(SpringRunner.class)
@SpringBootTest
public class WebSocketTest {

    @Autowired
    private MessageService messageService;

    @Test
    public void testGetById(){
        MyWebSocketMessage msg = this.messageService.getById(1L);
        System.out.println (msg);
    }
}

x-delayed-type
=================项目部署===========================
一、本地部署
npm run build:prod

server {
	listen 8882;
	server_name	localhost;
	root	/developer/java/jar/my12306/frontend/dist;
	index	index.html	index.htm;
	location / {
		try_files $uri	$uri/	/index.html?$args;
	}
	location /prod-api/ {
		proxy_pass	http://127.0.0.1:8880/;
	}
}
===============================
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Autowired
private TransactionDefinition transactionDefinition;

public JsonRest miaosha(){
	TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
	if(true){
		platformTransactionManager.rollback(transaction);
		throw new BusinessException("");
	}
	platformTransactionManager.commit(transaction);
}

通过feign+ribbon框架进行rpc调用:
string res = service.hello(), 按照http协议,数据格式也按照http协议的请求来做。
同时还需要序列化成字节数组,通过tcp连接发送过去。
非root账号启动nginx
sudo setcap cap_net_bind_service=
https://www.jianshu.com/p/dc814e8014b0
https://github.com/Nepxion/Banner banner生成  

window.location.pathname
window.history.pushState(null, null, 'bb')



import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpUtils {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static ConnectionPool pool = new ConnectionPool (50, 100, TimeUnit.SECONDS);
    public static OkHttpClient httpClient = new OkHttpClient.Builder ()
            .connectTimeout (30, TimeUnit.SECONDS)
            .readTimeout (120L, TimeUnit.SECONDS)
            .writeTimeout (120L, TimeUnit.SECONDS)
            .retryOnConnectionFailure (true)
            .connectionPool (pool).build ();

    public static ObjectRestResponse get(String url) {
        Request request = new Request.Builder()
                .url("http://localhost:8085/base/readFromExcel")
                .build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
        } catch (IOException e) {
            log.error("okHttp req url:{}, error", url, e);
            return ObjectRestResponse.fallbackDefault();
        } finally {
            if(response != null){
                response.close();
            }
        }
        String res = response.body().toString();
        return new ObjectRestResponse().data(res);
    }

    public static void doPost(String url, Map<String, String> requestMap){
        String json = com.alibaba.fastjson.JSON.toJSONString (requestMap);
        log.info("OkHttp req json {}", json);

        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            log.info ("httpClient res:{}", response.body().string());
        } catch (Exception e){
            log.error ("httpClient req error", e);
        }
    }
}

public class BaseException extends RuntimeException {
    private int status = 200;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public BaseException() {
    }

    public BaseException(String message, int status) {
        super(message);
        this.status = status;
    }

    public BaseException(String message) {
        super(message);
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseException(Throwable cause) {
        super(cause);
    }

    public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

/**
 * 当没有TomcatEmbeddedServletContainerFactory这个bean时,会加载它
 */
@Component
public class WebServerConfiguration implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        ((TomcatServletWebServerFactory)factory).addConnectorCustomizers (connector -> {
            Http11NioProtocol protocol = (Http11NioProtocol)connector.getProtocolHandler ();
            protocol.setKeepAliveTimeout (30000); //30s内没有请求则断开连接
            protocol.setMaxKeepAliveRequests (10000); //客户端发送1w个请求则断开连接
        });
    }
}
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value=Exception.class)
    public BaseResponse handleException(HttpServletRequest request, HttpServletResponse response){
        return BaseResponse.failed("服务器异常,请联系管理员");
    }

    @ExceptionHandler(value= BaseException.class)
    public BaseResponse handleBaseException(HttpServletRequest request, HttpServletResponse response, BaseException baseException){
        return BaseResponse.failed(baseException.getMessage());
    }
}

#等待队列长度
#server.tomcat.accept-count=1500
#默认值1w
#server.tomcat.max-connections=10000
#最大线程数(4h8g则800)
#server.tomcat.max-threads=1200
#最小线程数
#server.tomcat.min-space-threads=200
# jackson
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8



import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.HashMap;
import java.util.Map;

/**
 * mybatis代码生成
 */
public class CodeGeneration {

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("laihaonan");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖
        gc.setServiceName("%sService");    //去掉Service接口的首字母I
        gc.setIdType(IdType.AUTO); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式
        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8");
//        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("12345678");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        InjectionConfig injectionConfig = new InjectionConfig() {
            //自定义属性注入:abc
            //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        String moduleName = "file";
        pc.setModuleName(moduleName); //模块名
        pc.setParent("");
        pc.setController("controller");
        pc.setEntity("model");
        pc.setService("service");
        pc.setMapper("dao");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("t_file_info");//设置要映射的表名
//        strategy.setInclude("train_city", "train_number",
//                "train_number_detail","train_seat","train_station",
//                "train_traveller","train_user","train_user_traveller");//设置要映射的表名
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix("t" + "_");//设置表前缀不生成

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setLogicDeleteFieldName("is_deleted");//逻辑删除字段名
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);//去掉布尔值的is_前缀

        strategy.setVersionFieldName("version");//乐观锁列

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);
        mpg.execute();
    }
}

BANNER:
http://patorjk.com/software/taag/#p=display&f=Soft

Mybatis-generator-plugin:
\src\main\resources\generator\generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否生成注释代时间戳-->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/cloud?serverTimezone=Asia/Shanghai" userId="root" password="12345678">
        </jdbcConnection>
        <javaTypeResolver>
            <!--该属性可以控制是否强制DECIMAL和NUMERIC类型的字段转换为Java类型的java.math.BigDecimal,默认值为false,一般不需要配置。-->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="pojo" targetProject="src/main/java">
            <!--enableSubPackages:如果true,MBG会根据catalog和schema来生成子包。如果false就会直接用targetPackage属性。默认为false。-->
            <property name="enableSubPackages" value="true"/>
            <!--trimStrings:是否对数据库查询结果进行trim操作,如果设置为true就会生成类似这样public void setUsername(String username) {this.username = username == null ? null : username.trim();}的setter方法。默认值为false。-->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射xml文件存放位置-->
        <sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/main/resources/">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置(*Mapper.java)-->
        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
            type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
            type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
            type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成对应表及类名-->
        <table tableName="t_file_info" domainObjectName="FileInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <!--useActualColumnNames:如果设置为true,那么MBG会使用从数据库元数据获取的列名作为生成的实体对象的属性。 如果为false(默认值),MGB将会尝试将返回的名称转换为驼峰形式。 在这两种情况下,可以通过 元素显示指定,在这种情况下将会忽略这个(useActualColumnNames)属性。-->
            <property name="useActualColumnNames" value="true"/>
            <!-- 数据库表主键 -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>
    </context>
</generatorConfiguration>


    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- bootstrap.yml生效 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-context</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName><!--打jar包去掉版本号-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.48</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
10.json常用操作
        UserDto userDto = UserUtils.getCurrentUser();
        String[] excludeProperties = {"password"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludeProperties);
        System.out.println(JSONObject.toJSONString(userDto, excludefilter));

        String json = JSON.toJSONString(new ObjectRestResponse(Arrays.asList(userDto)));
        ObjectRestResponse<List<UserDto>> userDtoObjectRestResponse = JSON.parseObject(json, new TypeReference<ObjectRestResponse<List<UserDto>>>() {
        });
        List<UserDto> list = userDtoObjectRestResponse.getData();
        for (UserDto dto : list) {
            System.out.println(JSON.toJSONString(dto));
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值