程序员的工具包

 

一、Tools

JSON

  • JSON验证解析、ToBean转换:https://www.json.cn/json/json2java.html

@JsonProperty :Json别名

@JsonInclude:当属性的值为空(null或者"")时,不进行序列化。(也可以作用于类上)

@JsonIgnore:序列化时忽略属性

@JsonFormat:序列化时格式化时间

@JsonIgnoreProperties({"fieldName"}):作用于类上,表示序列化时忽略的属性(可多个)

 

MyBatis-Plus

  • Config类:
/**
 * 分页插件配置类
 */
@Configuration
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        return interceptor;
    }
}
  • Service层
public IPage<EventDto> getEventByCondition(EventMetaReqDto eventMetaReqDto) {
	// PageNums:页码 - PageSize:页面大小
    Page<EventDto> page = new Page<>(eventMetaReqDto.getPageNums(), eventMetaReqDto.getPageSize());
    IPage<EventDto> eventDtoList = eventMapper.queryEventByCondition(page, eventMetaReqDto);
    return eventDtoList;
}
  • Dao层
// xml中不需要其他额外的代码
IPage<EventDto> queryEventByCondition(IPage<EventDto> page, @Param("eventMetaReqDto") EventMetaReqDto eventMetaReqDto);

 

二、Utils

 

数据库

  1. MyBatis批量插入、更新
@Component
public class MyBatisBatchUtils {

    private static final int BATCH_SIZE = 1000;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 批量添加、更新数据
     *
     * @param data 要操作的实体链表
     * @param mapperClass 执行操作的mapper
     * @param function mapper执行的具体方法
     * @param <T> 实体类
     * @param <U> Mapper类
     */
    public <T, U, R> int batchUpdateOrInsert(List<T> data, Class<U> mapperClass, BiFunction<T, U, R> function) throws Exception {
        int i = 0;
        SqlSession batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        try {
            U mapper = batchSqlSession.getMapper(mapperClass);
            int size = data.size();
            for (T element : data) {
                function.apply(element, mapper);
                if ((i % BATCH_SIZE == 0) || i == size) {
                    batchSqlSession.flushStatements();
                }
                i++;
            }
            // 非事务环境下强制commit,事务情况下该commit相当于无效
            batchSqlSession.commit(!TransactionSynchronizationManager.isSynchronizationActive());
        } catch (Exception e) {
            batchSqlSession.rollback();
            throw new Exception(e);
        } finally {
            batchSqlSession.close();
        }
        return i;
    }
}

batchUtils.batchUpdateOrInsert(数据集合, xxxxx.class, (item, mapper实例对象) -> mapper实例对象.insert方法(item));

事务

  • 手动提交事务
// 需要先注入如下两个类
@Autowired
DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
TransactionDefinition transactionDefinition;

public void saveAll(){
    //开启事务
    TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
    try{
        this.save();
        //提交事务
        dataSourceTransactionManager.commit(transactionStatus);
    }catch(Exception e){
        //回滚事务
        dataSourceTransactionManager.rollback(transactionStatus);
    }
}

 

 

Spring

  1. 获取Bean
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

 

 

三、第三方接口

 

天气

  • 和风天气API:https://dev.qweather.com/docs/resource/icons/

    • 进入控制台创建应用,获取key
    • 使用key及url请求获取数据
  • RestTemplate获取天气信息

public WeatherInfoDto getWeatherInfo(Long location) {
    String key = "841e2ad14aac42259cc6eb630965f848";
    String url = "https://devapi.qweather.com/v7/weather/now?location={location}&key={key}";
	
	// 存放参数
    Map<String,String> params = new HashMap<>();
    params.put("key", key);
    params.put("location", String.valueOf(location));

    HttpHeaders headers = new HttpHeaders();
	//headers.add("accept-encoding", "gzip, deflate, br");
    headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
    headers.setContentType(MediaType.APPLICATION_JSON);
	
	// 存放header
    HttpEntity<String> entity = new HttpEntity<>(headers);

    byte[] responseBody = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class, params).getBody();
    String unGZipResult = unGZip(responseBody);

    WeatherInfoDto weatherInfoDto = WeatherInfoDto.builder().build();
    JSONObject jsonObject = JSONObject.parseObject(unGZipResult);

    try {
        weatherInfoDto = JSONObject.parseObject(jsonObject.getString("now"), WeatherInfoDto.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return weatherInfoDto;
}
  • WeatherInfoDto
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WeatherInfoDto {

    private String obsTime;
    private String temp;
    private String feelsLike;
    private String icon;
    private String text;
    private String wind360;
    private String windDir;
    private String windScale;
    private String windSpeed;
    private String humidity;
    private String precip;
    private String pressure;
    private String vis;
    private String cloud;
    private String dew;
}
  • Gzip文本解密
public static String unGZip(byte[] oResult) {
    try (InputStream inputStream = new ByteArrayInputStream(oResult);
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
        byte[] buf = new byte[4096];
        int len = -1;
        while ((len = gzipInputStream.read(buf, 0, buf.length)) != -1) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

 

 

节假日

 

  • 获取某天的节假日名
public String getHolidayNameByDate(LocalDate sourceDate) {
    int year = sourceDate.getYear();
    String date = sourceDate.format(DateTimeFormatter.ofPattern("MM-dd"));

	// 存放redis
    String redisKey = "holiday-" + year;
    if (redisUtil.hasKey(redisKey)) {
        Map<String, String> holidayMap = (Map<String, String>) redisUtil.get(redisKey);
        if (holidayMap.containsKey(date)) {
            return holidayMap.get(date);
        }
        return "";
    }

    Map<String, String> dateHolidayMap = getDateHolidayMap(year);

    redisUtil.set(redisKey, (Serializable) dateHolidayMap);
    if (dateHolidayMap.containsKey(date)) {
        return dateHolidayMap.get(date);
    }
    return "";
}
  • 获取全年节假日Map
private Map<String, String> getDateHolidayMap(int year) {
    String url = "http://timor.tech/api/holiday/year/" + year;

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.put("user-agent", Collections.singletonList("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"));

    HttpEntity<String> entity = new HttpEntity<>(headers);

    String responseBody = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
    JSONObject jsonObject = JSONObject.parseObject(responseBody);
    JSONObject jsonObject2 = JSONObject.parseObject(jsonObject.getString("holiday"));

    Map<String, String> dateHolidayMap = new HashMap<>();
    jsonObject2.forEach((k, v) -> {
        JSONObject jsonObject3 = JSONObject.parseObject(v.toString());

        String holidayName = jsonObject3.getString("name");
        String holidayTarget = jsonObject3.getString("target");
        dateHolidayMap.put(k, holidayTarget == null ? holidayName : holidayTarget);
    });
    return dateHolidayMap;
}