JAVA 相关知识点整理

序号
标题
内容
1  springboot 请求设置  
server:
tomcat:
# 等待队列最大长度
 accept-count: 1000
# 最大工作线程数
 max-threads: 1000
# 最小工作线程数
 min-spare-threads: 10
# 最大可被链接数
 max-connections: 2000
# 编码
 uri-encoding: UTF-8
2 springboot中获取容器并应用
1、
/**
* @Description 获取SpringBoot的容器
 * @Author cheney
* @Date 2019-03-14
**/
@Component
public class ApplicationContextRegister implements ApplicationContextAware {

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

}

2、

**
* @Description 获取通过Spring注入实现的bean
* @Author cheney
* @Date 2019-03-14
**/
public class SpringUtil {
private static final Logger logger = LoggerFactory.getLogger(SpringUtil.class);

private static ApplicationContext applicationContext = null;

public static void setApplicationContext(ApplicationContext ac) {
SpringUtil.applicationContext = ac;
 }

public static <T> T getBean(String beanName) {
try {
if(applicationContext.containsBean(beanName)){
return (T) applicationContext.getBean(beanName);
 }else{
return null;
 }
}catch (Exception e) {
logger.error("getBean error beanName {}",beanName, e);
return null;
 }
}
public static OrderAttachLocalService getOrderAttachLocalService() {
return applicationContext.getBean(OrderAttachLocalService.class);
 }
public static OrderAttachMapper getOrderAttachMapper() {
return applicationContext.getBean(OrderAttachMapper.class);
 }

public static ShopBaseInfoService getShopBaseService() {
return applicationContext.getBean(ShopBaseInfoService.class);
 }
public static HPosInfo getHPosInfo() {
return applicationContext.getBean(HPosInfo.class);
 }
public static RedisClient getRedisClient() {
return applicationContext.getBean(RedisClient.class);
 }
}

 

3、在不能注入的地方使用 

private OrderUploadSignService orderUploadSignService = SpringUtil.getBean("orderUploadSignService");

 

二、第二种方式

1、定义 SpringApplicationContext 实现ApplicationContextAware 

@Component
@Lazy(value = false)
public class SpringApplicationContext implements ApplicationContextAware {

private static 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);
 }

@Override
 public void setApplicationContext(ApplicationContext context) throws BeansException {
if (applicationContext == null) {
applicationContext = context;
 }
}
}

2、在使用的地方只接使用

UserService userService2= SpringApplicationContext.getBean(UserService.class);
String ss2=userService2.getUserNameByID(22);

 

三、在利用Controller 参数HttpServletRequest request 获取ApplicationContext 再获取对应的bean

// 设置静态 spring 对象
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
UserService userService3= ctx.getBean(UserService.class);
  mybatis-log控制台输出sql文 1、在application中加 就会将执行的sql输出在控制台。
logging:
level:
com.hualala.mendianbao.mapper: DEBUG

 

2、logback level设置DEBUG

<root level="DEBUG">
  循环迭代性能

1、外部for 循环和 .stream().foreach

简单数据外部for 循环性能比较 .stream()好,但有复杂处理两者相当

2.parallel处理比 for和.stream().froeach 性能好,但注意处理过程中使用的存储对象需要是线程安全的。

  Prometheus和Grafana

首先简单介绍Prometheus和Grafana
Prometheus是由SoundCloud开发的开源监控报警系统和时间序列数据库(TSDB),它是一个监控采集与数据存储框架(监控服务器端),具体采集什么数据依赖于Exporter(监控客户端),例如:采集MySQL的数据需要使用mysql_exporter,当Prometheus调用mysql_expoter采集到MySQL的监控指标之后,把采集数据存放到Prometheus所在服务器的磁盘数据文件中。它的各个组件基本都是用Golang编写的,对编译和部署十分友好,并且没有特殊依赖,基本都是独立工作的。
Grafana是一个高“颜值”的监控绘图程序,也是一个可视化面板(Dashboard)。Grafana的厉害之处除了高“颜值”,还支持多种数据源(支持Graphite、Zabbix、InfluxDB、Prometheus和OpenTSDB作为数据源)和灵活丰富的Dashboard配置选项(例如:可以把多个实例的相同采集项配置在一个展示框里),使其更易用,学习成本更低。从视觉上说,相比其他开源的监控系统,Grafana看起来要养眼得多。

   直接用JSONObject 创建对象
JSONObject foodJson = new com.alibaba.fastjson.JSONObject();
foodJson.put("orderKey", weChatOrderKey);

直接用JSONObject 创建对象

  idea生成、优化lamda表达式
boolean result= listUserinfo.stream().filter(x->x.getUserName()!=null && x.getUserName().equals("li")).findFirst().isPresent(); 在isPresent()方法上按 ALT+Enter

变化成:

boolean result= listUserinfo.stream().anyMatch(x->x.getUserName()!=null && x.getUserName().equals("li")); 
  枚举类定义

@Getter
public enum OrderStatusEnum {
WAiT("1","待接单"),ACCEPT("2","已接单"),SEND("3","已配送");

private String code;
private String name;

 OrderStatusEnum(String code, String name) {
this.code = code;
this.name = name;
 }
// 可以用orderStatusMap、listOrderStatus 做如是否存在枚举值
 public static Map<String,OrderStatusEnum> orderStatusMap=new HashMap<String, OrderStatusEnum>();
public static List<OrderStatusEnum> listOrderStatus=new ArrayList<>();
static {
// 将枚举所有值转换成 Hashmap
 Arrays.stream(OrderStatusEnum.values()).forEach(s->orderStatusMap.put(s.getCode(),s));
 listOrderStatus=Arrays.asList(OrderStatusEnum.values());
 }
}
  springboot新建测试

1、需要引入pom节点

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

2、测试类创建所需注解

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MultiDataSourceApplication.class)
public class ServiceTest {
// 可以直接注入
@Autowired
CustomerService customerService;
// 也可以注入 applicationContext,再通过 applicationContext.getBean(CustomerService.class); 获取实例
@Autowired
ApplicationContext applicationContext;
  liunx 命令查询生成新文件

grep -a '2022080912212013720163610264' application.2022-08-09-12.log > application02.txt

  设置jvm 堆内存大小

一、

java.lang.OutOfMemoryError: Java heap space Heap size 设置 JVM堆的设置是指java程序运行过程中JVM
可以调配使用的内存空间的设置.JVM在启动的时候会自动设置Heap size的值
,其初始空间(即-Xms)是物理内存的1/64,最大空间(-Xmx)是物理内存的1/4
。可以利用JVM提供的-Xmn -Xms -Xmx等选项可进行设置。
Heap size 的大小是Young Generation 和Tenured Generaion 之和。
提示:在JVM中如果98%的时间是用于GC且可用的Heap size 不足2%的时候将抛出此异常信息。
提示:Heap Size 最大不要超过可用物理内存的80%,一般的要将-Xms和-Xmx选项设置为相同,而-Xmn为1/4的-Xmx值。

Xmx20m -Xms5m -XX:HeapDumpOnOutofMemoryError -XX:HeapDumpPath=d:/a.dump

二、

java -Xmx72g -Xms72 -Xmn4g -Xss256m

-Xmx72g:设置JVM最大可用内存为72g。

 -Xms72g:设置JVM最小内存为72g。此值可以设置与-Xmx相同,以避免每次垃圾回收完成后JVM重新分配内存。

 -Xmn4g:设置年轻代大小为4G。整个堆大小=年轻代大小 + 年老代大小 + 持久代大小

 

   
1、使用commons-lang3 包下很多语法如:
StringUtils.isNumeric(cacheStatus); 
StringUtils.equalsIgnoreCase(table.getOrderKey(), saasOrderKey)

2、

常量与变量比较应该
Integer.valueOf(1).equals(request.getIncludeDeliverOverTime())
不应该
1==request.getIncludeDeliverOverTime() 当request.getIncludeDeliverOverTime() 为null时会报错

 

  git 临时保存,切换

git stash save 'no commit';

git stash list
git stash pop

  class path和文件路径

1、  工具包hutool.jar里面有强大的基础工具封装,可以直接通过Props类获取资源文件。 

2、  使用classpath:这种前缀,就只能代表一个文件;使用classpath*:这种前缀,则可以代表多个匹配的文件。     

用法1:classpath:xxxx.xml  (匹配单文件)

用法2:classpath*:**/mapper/*Mapper.xml (匹配多文件)

3、

// 获取编译后 .class 所在目录,Resource下的文件也在该目录存储

ClassLoader classLoader = FirstController.class.getClassLoader();
Enumeration<URL> config = classLoader.getResources("");
URL url = config.nextElement();

  针对一个方法用泛型
public <T> void getStr(T s1){
System.out.println("it is method");
}
  查看表结构 show create table tbl_mendian_order_pay
  日期json序列化和反序列化 格式化
<artifactId>jackson-annotations</artifactId>
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
 
* 开票日期
*/
@DateTimeFormat(pattern = "yyyy-MM-dd") // 用于接收日期
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") // 用于返回输出日期格式
private Timestamp invoiceDate2;
  git 项目初始化仓库

pre:创建 gitee 账号
1)配置你的用户名和邮箱,如果配置过就不用该步骤:
git config --global user.name "xxx"
git config --global user.email "xxx"

1、 gitee 上创建仓库
ps:如果项目代码本身就是git项目理解可以不用执行[git init]
“git init”命令用于创建git 项目,其可以在一个已有的非git项目的根目录下执行,把已有项目初始化成为git仓库,也可以用于初始化一个空的目录为git仓库
2、将项目关联到 git remote add origin https://gitee.com/liyanbo123/work-code.git

3、将项目推送到仓库 git push -u origin master


刚创建仓库 提示信息
https://gitee.com/liyanbo123/work-code

  json 转换List数组
8、json 转换List 对象
String jsonD="[{\"distance\":{\"text\":\"19.5公里\",\"value\":19453},\"duration\":{\"text\":\"12分钟\",\"value\":729}}]";
Type type = new TypeToken<List <RouteMatrixVo>>() {
}.getType();
List<MatrixVo> listData = gson.fromJson(jsonD, type);
或
    
List<OrderGoodsVo> goodsList = JSONObject.parseArray(goodsData,OrderGoodsVo.class);

 

  springboot 读取 resource目录下文件
//        File file=new File("F:\\HualalaWork\\xiyipos\\pos-web\\src\\main\\resources\\问题.txt");
//        读取 resource目录文件
//        File file=new File("src/main/resources/问题.txt");// 仅能应用于开发环境
        File file = ResourceUtils.getFile("classpath:问题.txt");//在linux环境中无法读取。(不通用)
        Resource resource = new ClassPathResource("问题.txt");     // 通用
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream in = null;
        byte[] tempByte = new byte[1024];
        int byteread = 0;
        System.out.println("以字节为单位读取文件内容,一次读多个字节:");
//        in = new FileInputStream(file);
        in = resource.getInputStream();
        while ((byteread = in.read(tempByte)) != -1) {
//            System.out.write(tempByte, 0, byteread);
            System.out.println("new String(tempByte) = " + new String(tempByte)); 
        }

 

   json 直接转换成 HashMap Map<String,String> jsonObject = (Map<String, String>) JSONObject.parse(jsonStr); // 可以将json字符串直接转换成HashMap
 
posted @ 2022-11-24 22:57  xiaoBai1001  阅读(24)  评论(0编辑  收藏  举报