jdk8-菜单递归-工具类-ip-Tomcat-加载器
转map
Map<String,MemberInfoAllResponse> userMap = users.stream().collect(Collectors.toMap(MemberInfoAllResponse::getUserId,o -> o,(key1, key2) -> key1));
// 使用flatMap将内部列表展平成一个单一列表
List<List<String>> listOfLists ;
List<String> flatList = listOfLists.stream()
.flatMap(List::stream) // 使用List的stream方法将每个列表转换成流,然后合并
.collect(Collectors.toList());
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 使用peek打印流中的元素,然后使用limit和skip获取特定元素
List<Integer> result = numbers.stream()
.peek(System.out::println) // 打印每个元素 只打印到5
.skip(2) // 跳过前两个元素
.limit(3) // 获取接下来的三个元素
.collect(Collectors.toList()); // 收集结果
List<Integer> numbers = Arrays.asList(1, 2, 3);//, 4,5,6,7,8,9,10
long sum = numbers.stream().mapToLong(i -> i).sum();
奇偶分组、排序然后提取每组中最小和最大值的案例
Map<Boolean,List<Integer>> result2 = numbers.stream().collect(Collectors.groupingBy(i->i%2==0
,Collectors.collectingAndThen(Collectors.toList(),list -> {
list.sort(Integer::compareTo);
return Lists.newArrayList(list.get(0),list.get(list.size()-1));
})
));
stream流 https://mp.weixin.qq.com/s/U3XS3J2tHtpmeXqUB5QIYg
格式化返回日期字段 com.fasterxml.jackson.annotation @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date createTime;
1,当执行new操作时候 2,当执行Class.forName(“包路径 + 类名”)\ Class.forName(“包路径 + 类名”, ClassLoader)\ ClassLoader.loadClass(“包路径 + 类名”) 以上情况都会触发类加载器去类加载对应的路径去查找对应的.class文件,并创建Class对象,不过第((2))方式加载字节码到内存后生产的只是一个Class对象,要得到具体的对象实例还需要使用Class对象的newInstance()方法来创建具体实例. 1,AppClassLoader 应用类加载器,又称为系统类加载器,负责在JVM启动时,加载来自在命令java中的classpath或者java.class.path系统属性或者CLASSPATH操作系统属性所指定的JAR类包和类路径 2,ExtClassLoader 称为扩展类加载器,主要负责加载Java的扩展类库,默认加载JAVA_HOME/jre/lib/ext/目录下的所有jar包或者由java.ext.dirs系统属性指定的jar包.放入这个目录下的jar包对AppClassLoader加载器都是可见的(因为ExtClassLoader是AppClassLoader的父加载器,并且Java类加载器采用了委托机制) 3,BootstrapClassLoader 称为启动类加载器,是Java类加载层次中最顶层的类加载器,负责加载JDK中的核心类库,如:rt.jar、resources.jar、charsets.jar等 Bootstrap ClassLoader是由C/C++编写的,它本身是虚拟机的一部分,所以它并不是一个JAVA类,也就是无法在java代码中获取它的引用,JVM启动时通过Bootstrap类加载器加载rt.jar等核心jar包中的class文件,之前的int.class,String.class都是由它加载。然后呢,我们前面已经分析了,JVM初始化sun.misc.Launcher并创建Extension ClassLoader和AppClassLoader实例。并将ExtClassLoader设置为AppClassLoader的父加载器
1,HTTP1.1 默认保持长连接 数据传输完成了保持 TCP 连接不断开(不发 RST 包、不四次握手),等待在同域名下继续用这个通道传输数据;相反的就是短连接
它可以在传输数据后仍保持连接,当客户端需要再次获取数据时,直接使用刚刚空闲下来的连接而无需再次握手
2,Keep-Alive不会永久保持连接,它有一个保持时间,可以在不同的服务器软件(如Apache)中设定这个时间。实现长连接要客户端和服务端都支持长连接
server:
name: OTC-Esign-Web
port: 8090
tomcat:
max-threads: 1000 最大工作线程数,默认200
min-spare-threads: 30 最小工作空闲线程数 默认10
max-connections: 默认值是10000
accept-count: 等待队列长度,默认100
max-connections Tomcat在任意时刻能接收和处理的最大连接数
注意这个参数并不是设置在线程池上的,而是在tomcat的Acceptor类(专门处理连接的线程类)来控制的
如果设置为-1,则禁用maxconnections功能,表示不限制tomcat容器的连接数
maxConnections和accept-count的关系为:当连接数达到最大值maxConnections后,系统会继续接收连接,但不会超过 accept-count 的值
springboot内置的tomcat目前默认是基于NIO来实现的
maxKeepAliveRequests 长连接最大支持的请求数 -1时,表示没有最大请求数限制;如果其值被设置为 1,将会禁用掉HTTP长连接
keepAliveTimeout 此选项为TCP连接保持时长,单位为毫秒。表示在下次请求过来之前,该连接将被Tomcat保持多久
https://www.csdn.net/tags/OtTaYgysNjM0MzctYmxvZwO0O0OO0O0O.html 设置内部长连接
min-spare-threads: 100
#最小工作空闲线程数,默认10, 适当增大一些,以便应对突然增长的访问量
max-threads: 6000
#最大工作线程数,默认200
每一次HTT请求到达Web服务,tomcat都会创建一个线程来处理该请求, 增加线程是有成本的,更多的线程,不仅仅会带来更多的线程上下文切换成本,而且意味着带来更多的内存消耗。JVM中默认情况下在创建新线程时会分配大小为1M的线程栈
1核2g内存为200,线程数经验值200;4核8g内存,线程数经验值800。
Lambda表达式
List<Menu> menuList = ....;
//获取父节点
return menuList.stream()
.filter(m -> StringUtils.equals("0", m.getParentId()))
.peek(m -> m.setChildren(getChildren(m, menuList)))
.collect(Collectors.toList())
//递归查询节点
public List<Menu> getChildren(Menu root, List<Menu> list) {
return list.stream()
.filter(m -> Objects.equals(m.getParentId(), root.getId()))
.peek(m -> m.setChildren(getChildren(m, list)))
.collect(Collectors.toList());
}
peek对一个对象进行操作的时候,对象不变,但是可以改变对象里面的值
map操作是对元素进行了转换
filter 过滤 map 收集
Optional<ResultVo> ops = vs.stream().filter(a -> "message2".equals(a.getMessage())).findFirst();
System.out.println(ops.get());
System.out.println(ops.map(ResultVo::getData).orElse("NULL"));//为空则返回默认值
数据从对象A的集合转到对象B的集合
List<MyTest> mts = data.stream().map(z -> new MyTest(z.getNoteId(),z.getNoteName())).collect(Collectors.toList());
//运算
现在想获取User的身份证号码
List<User> users;
List<String> idcards= users.stream().map(User::getIdcard).collect(Collectors.toList())
数组所有元素,按某种规律计算:
List<Integer> num = Arrays.asList(1,2,3,4,5);
List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
System.out.println(collect1);
List<String> list= Arrays.asList("a", "b", "c", "d");
List<String> collect =list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(collect); //[A, B, C, D]
//过滤
//所有名字叫hanmeimei的集合
List<Object> firstObject= ObjectList.stream() .filter(a -> "hanmeimei".equals(a.getUserName())) .collect(Collectors.toList());
//所有名字为空的集合
List<Object> firstObject= ObjectList.stream() .filter(a -> StringUtils.isEmpty(a.getUserName())).collect(Collectors.toList());
//排序
List<User> userss = users.stream().sorted(new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
return u1.getId() - u2.getId();
}
}).collect(Collectors.toList());
//去重
.distinct()
// 统计 总数 总和 最大 最小 平均
.mapToInt(i -> i).summaryStatistics() flatMapToInt
//flatMap
Stream<List<Integer>> stream = Stream.of(Arrays.asList(1,2), Arrays.asList(3, 4, 5));
stream.flatMap(list -> list.stream()).forEach(i -> System.out.println(i));
实现List<Data1>和List<Data2>根据Id进行连接,将连接结果输出为一个List<Data3>:
List<UserResult> userResultS = users.stream().flatMap(x -> userVos.stream()
.filter(y -> x.getId() == y.getId())
.map(y -> new UserResult(x.getName(),x.getIdCard(),y.getNameVo(),y.getIdCardVo())))
.collect(Collectors.toList());
System.out.println(userResult
Map<Integer, ListContainer> map = Maps.newHashMap();
List<AClass> aClassList1 = Lists.newArrayList();
AClass aClass = new AClass(1, "zhuoli1", "haha1");
aClassList1.add(aClass);
aClassList1.add(new AClass(2, "zhuoli2", "haha2"));
aClassList1.add(new AClass(3, "zhuoli3", "haha3"));
List<AClass> aClassList2 = Lists.newArrayList();
aClassList2.add(aClass);
aClassList2.add(new AClass(5, "zhuoli5", "haha5"));
aClassList2.add(new AClass(6, "zhuoli6", "haha6"));
/*交集*/
/*[AClass(id=1, name=zhuoli1, description=haha1)]*/
List<AClass> intersectResult = aClassList1.stream().filter(aClassList2::contains).collect(Collectors.toList());
System.out.println(intersectResult);
/*并集*/
List<AClass> unionResult = Stream.of(aClassList1, aClassList2).flatMap(Collection::stream).distinct().collect(Collectors.toList());
assertEquals(unionResult.size(), 5);
/*差集*/
/*[AClass(id=2, name=zhuoli2, description=haha2), AClass(id=3, name=zhuoli3, description=haha3)]*/
List<AClass> differenceResult = aClassList1.stream().filter(x -> !aClassList2.contains(x)).collect(Collectors.toList());
System.out.println(differenceResult);
map.put(1, new ListContainer(aClassList1));
map.put(2, new ListContainer(aClassList2));
/*合并多个list*/
List<AClass> aClassListResult = map.values().stream().flatMap(listContainer -> listContainer.getLst().stream()).collect(Collectors.toList());
/*注意跟并集的区别*/
assertEquals(aClassListResult.size(), 6);
System.out.println(aClassListResult);
集合以某个元素分组 groupingBy
private List<String> afterJava8(List<Dish> dishList) {
return dishList.stream()
.filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴
.sorted(comparing(Dish::getCalories)) //根据卡路里进行排序
.map(Dish::getName) //提取菜肴名称
.collect(Collectors.toList()); //转换为List
}
private static Map<String, List<Dish>> afterJdk8(List<Dish> dishList) {
return dishList.stream().collect(groupingBy(Dish::getType));
}
https://mp.weixin.qq.com/s/FI1Ue6_ut5YVLg-rmrYAqA
filter(过滤)
findFirst(查找第一个) findAny(查找任意一个) anyMatch(任意匹配) noneMatch(空匹配) allMatch(全匹配)
User user = list.stream().filter(u -> u.getAge() > 30).findFirst().get();
com.alibaba.fastjson.JSONObject
User user = JSONObject.parseObject("{id:'111',name:'namess'}",User.class);
List<User> users = JSONObject.parseArray("[{id:'111',name:'namess'}]",User.class);
User respValue = JSON.parseObject("{id:'111',name:'namess'}", new TypeReference<User>(){});
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
//同步数据去重 insurantsPerson = insurantsPerson.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getIdType() + ";" + o.getIdCardNo()))), ArrayList::new)); //存在关系为父母性别为男的 boolean hasParentM = insurantList.stream().filter(insurant -> insurant.getRelation() == (byte)EnumInsurantRelation.PARENT.getCode() && insurant.getSex() == EnumsSex.M.getCode() ).findAny().isPresent(); // 分组 Map<String,String> map = customerOrderList.stream().collect(Collectors.toMap(CustomerOrderRequestVo::getOrderId,CustomerOrderRequestVo::getPolicyNo,(key1, key2) -> key2));
工具类
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
list集合拼接成以逗号分隔的字符串
String join = list.stream().collect(Collectors.joining(","));
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(date);
Date date2 = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss");
System.out.println(date2);
// 计算一个小时后的日期
Date date3 = DateUtils.addHours(new Date(), 1);
// 对象转map
Map<String, String> map = BeanUtils.describe(user);
System.out.println(map); // 输出 {"id":"1","name":"yideng"}
// map转对象
User newUser = new User();
org.apache.commons.beanutils.BeanUtils.populate(newUser, map);
System.out.println(newUser); // 输出 {"id":1,"name":"yideng"}
File file = new File("demo1.txt");
// 读取文件
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
// 写入文件
FileUtils.writeLines(new File("demo2.txt"), lines);
// 复制文件
FileUtils.copyFile(srcFile, destFile);
服务器ip地址:多次反向代理后会有多个ip值,第一个ip才是真实ip
private static final String IP_127_0_0_1 = "127.0.0.1";
private static final String UNKNOWN_IP_ADDRESS = "unknown";
private static final String AUTO_PAHAOCHE_PROXY = "X-Real-IP";
private static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
private static final String PROXY_CLIENT_IP = "Proxy-Client-IP";
private static final String X_FORWARDED_FOR = "x-forwarded-for";
logger.info("getIp:all:AUTO_PAHAOCHE_PROXY:"+request.getHeader(AUTO_PAHAOCHE_PROXY)+",X_FORWARDED_FOR:"+request.getHeader(X_FORWARDED_FOR)+",PROXY_CLIENT_IP:"+request.getHeader(PROXY_CLIENT_IP)+",WL_PROXY_CLIENT_IP:"+request.getHeader(WL_PROXY_CLIENT_IP)+","
+request.getRemoteAddr());
String ip = request.getHeader("X-Forwarded-For");
logger.info("getIp:"+ip+","+request.getHeader("X-Real-IP"));
if(StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = request.getHeader("X-Real-IP");
logger.info("getIp2:"+ip);
if(StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
logger.info("getIp3:"+request.getRemoteAddr());
return request.getRemoteAddr();
}
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
logger.warn("get address error", e);
}
if (inet != null) {
String ipAddress = inet.getHostAddress();
logger.info("getIp:ipAddress:"+ipAddress);
}
获取客户端ip
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null && ip.indexOf(",") > 0 && ip.split(",").length > 1) {
ip = ip.split(",")[0];
}
return ip;

浙公网安备 33010602011771号