upj

1.Git操作命令

Git global setup
git config --global user.name "xxx"
git config --global user.email "xxx2035@163.com"
Create a new repository
git clone xxx.git
cd data_filtering
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
Push an existing folder
cd existing_folder
git init
git remote add origin xxx.git
git add .
git commit -m "Initial commit"
git push -u origin master
    

Push an existing Git repository
cd existing_repo
git remote rename origin old-origin
git remote add origin xxx.git
git push -u origin --all
git push -u origin --tags

2.getUrlWithParams 拼接功能

public static String getUrlWithParams(String url, Map<String, String> params) {
    String paramsString = url;
    if (!paramsString.contains("?")) paramsString += "?";
    for (Map.Entry<String, String> entry:params.entrySet()) {
        if (!paramsString.endsWith("&")) paramsString += "&";
        paramsString += entry.getKey()+"="+entry.getValue()+"&";
    }
    return paramsString.substring(0,paramsString.length()-1);
}

for (Map.Entry<String, String> entry:params.entrySet()) {}

3.NumberFormat

java对文字, 数字的格式化,是有一个公共的父类的Format
NumberFormat和DecimalFormat都是它的子类*关于数字的*
DateFormat和SimpleDateFormat也是它的子类关于文字的

NumberFormat和DecimalFormat是线程不安全的

NumberFormat帮助您格式化和解析任何区域设置的数字。您的代码可以完全独立于小数点,千位分隔符的区域设置约定,甚至是使用的特定十进制数字,或者数字格式是否为十进制。

DecimalFormat是NumberFormat十进制数字格式的具体子类 。它具有多种功能,旨在解析和格式化任何语言环境中的数字,包括支持西方,阿拉伯语和印度语数字。它还支持不同类型的数字,包括整数(123),定点数(123.4),科学记数法(1.23E4),百分比(12%)和货币金额(123美元)。所有这些都可以本地化。
获取NumberFormat实例

//创建 一个整数格式 地区用系统默认的
NumberFormat integerNumber = NumberFormat.getIntegerInstance(Locale.getDefault());

使用getInstance或getNumberInstance获取正常的数字格式。
使用getIntegerInstance得到的整数格式。
使用getCurrencyInstance来获取货币数字格式。
使用getPercentInstance获取显示百分比的格式
NumberFormat numberFormat = NumberFormat.getInstance();
// 设置精确到小数点后5位
numberFormat.setMaximumFractionDigits(4);
numberFormat.setRoundingMode(RoundingMode.DOWN);
String res = numberFormat.format((float) managedCount / (float) netElementTotal * 100);
String netElementRate = res + "%";
result.put("netElementRate", netElementRate);

4. java8分别对于Map的key和value值进行排序

1、map 根据value排序

Map<String,BigDecimal> map =new HashMap<>();
map.put(“one”, 0.08);
map.put(“two”, 0.1);
map.put(“three”, 0.2);
map.put(“four”, 0.91);
上面是项目中的一个中间结果,我们需要对这个map根据value值倒序排序,下面给出工具类:

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
 
        map.entrySet().stream()
                .sorted(Map.Entry.<K, V>comparingByValue()
                        .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }

2、map 根据key排序
想根据map的key进行排序,需要对上面的工具类进行小小的修改,代码如下:

public <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) {        Map<K, V> result = new LinkedHashMap<>();         map.entrySet().stream()                .sorted(Map.Entry.<K, V>comparingByKey()                        .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));        return result;    }

我们可以看到,如果我们需要根据key排序,就需要让key 继承 Comparable ,也就说我们需要对待排序的字段继承 Comparable接口。另一个问题就是,上面的这种写法排序效果是 降序排序,如果我们需要升序排序的话,只需要将上面的.reversed()关键字限制去掉即可。

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {        Map<K, V> result = new LinkedHashMap<>();         map.entrySet().stream()                .sorted(Map.Entry.<K, V>comparingByValue()                        ).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));        return result;    }

5.时间(7天)

  private List<String> getDaysBetwwen(int days) {        List<String> dayss = new ArrayList<>();        Calendar start = Calendar.getInstance();        start.setTime(getDateAdd(days));        Long startTIme = start.getTimeInMillis();        Calendar end = Calendar.getInstance();        end.setTime(new Date());        Long endTime = end.getTimeInMillis();        Long oneDay = 1000 * 60 * 60 * 24l;        Long time = startTIme;        while (time <= endTime) {            Date d = new Date(time);            DateFormat df = new SimpleDateFormat("yyyyMMdd");            dayss.add(df.format(d));            time += oneDay;        }        return dayss;    }
private Date getDateAdd(int days) {        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");        Calendar c = Calendar.getInstance();        c.add(Calendar.DAY_OF_MONTH, -days);        return c.getTime();    }
List<DcResManageResult> dcResManageResults = dcResManageResults1.stream().sorted(Comparator.comparing(DcResManageResult::getCheckItem)).collect(Collectors.toList());

6.日期比较方式之Date的after和before

1. after/before

使用after/before进行日期比较时注意:
date1.after(date2)
当date1大于date2时,返回true,当小于等于时,返回false;

date1.before(date2)
当date1小于date2时,返回true,当大于等于时,返回false.

!currentDate.before(startDate) && !currentDate.after(engMPTask.getEndDate())

相当于

currentDate.getTime() >= startDate.getTime() && currentDate.getTime() <= engMPTask.getEndDate().getTime()

2. 用date.getTime() 返回long,再进行比较

if(dt1.getTime() < dt2.getTime()) {}

//-------------------
ZonedDateTime.now():获取当前时间

3. compareTo

两个Date类型的变量可以通过compareTo方法来比较。此方法的描述是这样的:如果参数 Date 等于此 Date,则返回值 0;如果此 Date 在 Date 参数之前,则返回小于 0 的值;如果此 Date 在 Date 参数之后,则返回大于 0 的值。
实际上比较的是自1970 年 1 月 1 日 00:00:00 GMT以来的毫秒数。毫秒数越大的时间越大。

String DateStr1 = "2011-10-1 10:20:16";String DateStr2 = "2011-10-07 15:50:35";DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date dateTime1 = dateFormat.parse(DateStr1);Date dateTime2 = dateFormat.parse(DateStr2);int i = dateTime1.compareTo(dateTime2); System.out.println(i < 0);

4. SimpleDateFormat的format方法将日期型转化成时间或日期的字符串,然后再比较字符串

日期型转换为字符串:

SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS毫秒");  String str=sdf.format(date);

beginTime.compareTo(endTime)<0时,开始时间小于结束时间

注意:如果一个日期格式是2016-01-01,但是另一个日期格式是2016-1-1时,直接使用字符串进行比较就会存在问题。

7.三种加载配置文件的方式

三种方式加载properties配置文件
1.三种加载方式的编码

具体代码如下所示:

public class PropertiesLoader {	public static void main(String[] args) throws IOException {		//方式一 、使用属性对象Properties和文件输入流对象FileInputStream加载properties配置文件。		Properties properties = new Properties();//创建属性对象		FileInputStream fileInputStream = new FileInputStream("D:\\xxxx.properties");//创建文件输入流对象		properties.load(fileInputStream);		System.out.println("dispatcher.conn.thread="+properties.getProperty("dispatcher.conn.thread"));		System.out.println("dispatcher.request.thread="+properties.getProperty("dispatcher.request.thread"));		System.out.println("dispatcher.response.thread="+properties.getProperty("dispatcher.response.thread"));        		//注意:此处可以获取带双引号的值,需要双等号。		System.out.println("dispatcher.response.thread1="+properties.getProperty("dispatcher.response.thread1"));				//注意:此处获取的值为null,因为value被双引号包裹。		System.out.println("dispatcher.response.thread2="+properties.getProperty("dispatcher.response.thread2"));		System.out.println("===================================分割线1===================================");						//方式二、通过属性对象Properties和类加载器加载properties配置文件,注意配置文件的位置必须在src目录下。		Properties properties2 = new Properties();		InputStream in = PropertiesLoader.class.getClassLoader().getResourceAsStream("xxxx.properties");		properties2.load(in);		System.out.println("dispatcher.conn.thread="+properties2.getProperty("dispatcher.conn.thread"));		System.out.println("dispatcher.request.thread="+properties2.getProperty("dispatcher.request.thread"));		System.out.println("dispatcher.response.thread="+properties2.getProperty("dispatcher.response.thread"));				//注意:此处可以获取带双引号的值,需要双等号。		System.out.println("dispatcher.response.thread1="+properties2.getProperty("dispatcher.response.thread1"));		//注意:此处获取的值为null,因为value被双引号包裹。		System.out.println("dispatcher.response.thread2="+properties2.getProperty("dispatcher.response.thread2"));						System.out.println("===================================分割线2===================================");		//方式三、通过资源包对象ResourceBundle和基名(即文件前缀名)加载properties配置文件,注意配置文件的位置必须在src目录下。		ResourceBundle bundle = ResourceBundle.getBundle("xxxx2");		System.out.println("dispatcher.conn.thread="+bundle.getString("dispatcher.conn.thread"));		System.out.println("dispatcher.request.thread="+bundle.getString("dispatcher.request.thread"));		System.out.println("dispatcher.response.thread="+bundle.getString("dispatcher.response.thread"));				//注意:此处可以获取带双引号的值,需要双等号。		System.out.println("dispatcher.response.thread1="+bundle.getString("dispatcher.response.thread1"));				//注意此处会报异常,因为value被双引号包裹。		System.out.println("dispatcher.response.thread2="+bundle.getString("dispatcher.response.thread2"));			}}
Resource resource = resourceLoader.getResource("classpath:resource.properties");        InputStream is = resource.getInputStream();        InputStreamReader isr = new InputStreamReader(is);        BufferedReader br = new BufferedReader(isr);        String data = null;        while((data = br.readLine()) != null) {            System.out.println(data);        }//---------------------------------------------------------------------new BufferedReader(new InputStreamReader(resourceLoader.getResource("classpath:resource.properties").getInputStream)))
  InputStream in = null;        Properties properties = null;        try {            in = fds.class.getResourceAsStream("/config/ems.yml");            System.out.println(in);            properties = new Properties();        } catch (Exception e) {            e.printStackTrace();        }        try {            properties.load(new InputStreamReader(in,"utf-8"));        } catch (IOException e) {            e.printStackTrace();        }        String logFilePath = properties.getProperty("logFilePath");        System.out.println(logFilePath);

8. es 动态索引

关键技术点: Spel表达式 (通过调用方法来获取新的索引名,方法内处理新索引名的生成逻辑)

**实体类部分代码**

从表达式中可以看出:esConfig 是一个bean,调用了getXX方法。

@Document(indexName = "#{esConfig.getApiCallIndexName()}")public class ApiCallRecord {    /**     * 平台流水号     */    @Id    @Field(type = FieldType.Keyword)    private String transId;    。。。。。。    }

动态索引Bean代码

将改类注册成Bean,名称为“esConfig”,其中apiCallIndexNamePrefix,是索引的前缀(为了通用,让它从配置文件取,如果没有那么就设置默认值“api_call_rec_”),方法中的逻辑就是生成逻辑,这样就能够生成api_call_rec_yyyy_MM这样的索引了。

@Component(value = "esConfig")public class ElasticSearchConfiguration {    @Value("${esConfig.apiCallIndexName:api_call_rec_}")    private String apiCallIndexNamePrefix;    public String getApiCallIndexName() {        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM");        return apiCallIndexNamePrefix + LocalDateTime.now().format(formatter);    }}

从Kibana中也能看到确实是生成了动态索引(我最开始是获取当前时间“秒”来测试的,每次处理逻辑后基本都会有新的索引创建。)

9. CollectionUtils.isEmpty(集合)

package org.apache.commons.collections;
源码如下:

public static boolean isEmpty(Collection coll) {        return coll == null || coll.isEmpty();    }

CollectionUtils.isEmpty(集合) 用来对集合null和空的判断

10.数据库地址

?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
posted @ 2021-08-05 11:59  泊月居  阅读(185)  评论(0编辑  收藏  举报