0%

进程操作

  • netstat -aon|findstr “8080”

TCP 127.0.0.1:80 0.0.0.0:0 LISTENING 2448
端口被进程号为2448的进程占用,继续执行下面命令:

  • tasklist|findstr “2448”

thread.exe 2016 Console 0 16,064 K

很清楚,thread占用了你的端口,Kill it

  • taskkill -F -PID 2448

如果第二步查不到,那就开任务管理器,进程—查看—选择列—pid(进程位标识符)打个勾就可以了

查看文件md5值

1
2
3
certutil -hashfile filename MD5
certutil -hashfile filename SHA1
certutil -hashfile filename SHA256

TCP and UDP

  • TCP stands for Transmission Control Protocol and UDP stands for User Datagram Protocol, and both are used extensively to build Internet applications.
  • The protocol which is the core of internet, HTTP is based on TCP.

why

why Java developer should understand these two protocols in detail is that Java is extensively used to write multi-threaded, concurrent and scalable servers.

where

While UDP is more suitable for applications that need fast, efficient transmission, such as games. UDP’s stateless nature is also useful for servers that answer small queries from huge numbers of clients. In practice, TCP is used in finance domain e.g. FIX protocol is a TCP based protocol, UDP is used heavily in gaming and entertainment sites.

how

  • TCP is connection oriented, reliable, slow, provides guaranteed delivery and preserves the order of messages

  • UDP is connectionless, unreliable, no ordering guarantee, but a fast protocol.

  • TCP overhead is also much higher than UDP, as it transmits more metadata per packet than UDP. that header size of Transmission control protocol is 20 bytes, compared to 8 bytes header of User Datagram protocol.

  • Use TCP, if you can’t afford to lose any message, while UDP is better for high-speed data transmission, where loss of a single packet is acceptable e.g. video streaming or online multiplayer games.

build

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Computer

public class Computer {

//required parameters
private String HDD;
private String RAM;

//optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;


public String getHDD() {
return HDD;
}

public String getRAM() {
return RAM;
}

public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}

public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}

private Computer(ComputerBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}

//Builder Class
public static class ComputerBuilder{

// required parameters
private String HDD;
private String RAM;

// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;

public ComputerBuilder(String hdd, String ram){
this.HDD=hdd;
this.RAM=ram;
}

public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}

public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}

public Computer build(){
return new Computer(this);
}

}
}

//ComputerBuilder

import com.journaldev.design.builder.Computer;

public class TestBuilderPattern {

public static void main(String[] args) {
//Using builder to get the object in a single line of code and
//without any inconsistent state or arguments management issues
Computer comp = new Computer.ComputerBuilder(
"500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
}
} ```

ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation, and data access.

The advantages of using ORM over JDBC

  • Application development is fast.
  • Management of transaction.
  • Generates key automatically.
  • Details of SQL queries are hidden.

Hibernate Architecture

  • Java application layer
  • Hibernate framework layer
  • Backhand api layer
  • Database layer

Hibernate Application Architecture:

JDBC (Java Database Connectivity)

JTA (Java Transaction API)

JNDI (Java Naming Directory Interface)

Elements of Hibernate Architecture

  • Configuration

    • Database Connection − This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
    • Class Mapping Setup − This component creates the connection between the Java classes and database tables.
  • SessionFactory

    SessionFactory is a thread-safe object, many threads cannot access it simultaneously.

  • Session

    • It maintains a connection between the hibernate application and database.It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
    • Session is not a thread-safe object, many threads can access it simultaneously. In other words, you can share it between threads.
  • Transaction

  • ConnectionProvider

  • Query

    Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

  • Criteria

    Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.

About SQL

  • SQL query created in Hibernate(Native sql)

    Session.createSQLQuery

    1
    2
    3
    Session.createSQLQuery()
    //The method createSQLQuery() creates Query object using the native SQL syntax.
    Query query = session.createSQLQuery("Select * from Student");
  • HQL query

    Session.createQuery

    1
    2
    3
    Session.createQuery()
    //The method createQuery() creates Query object using the HQL syntax.
    Query query = session.createQuery("from Student s where s.name like 'k%'");
  • criteria query

    Session.createCriteria

    1
    2
    3
    Session.createCriteria()
    //The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API.
    Criteria criteria = session.createCriteria(Student.class);

HQL vs Criteria

  • HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the data, we cannot perform non-select operations using criteria
  • HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
  • HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
  • Criteria used to take more time to execute then HQL
  • With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.

Caching

Cache memory stores recently used data items in order to reduce the number of database hits as much as possible.

  • First level Cache

    Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

  • Second level Cache

    Hibernate Second Level cache is disabled by default but we can enable it through configuration. Currently EHCache and Infinispan provides implementation for Hibernate Second level cache and we can use them.

  • Query Cache

    Hibernate can also cache result set of a query. Hibernate Query Cache doesn’t cache the state of the actual entities in the cache; it caches only identifier values and results of value type. So it should always be used in conjunction with the second-level cache.


types of association mapping

  1. One to One

  2. One to Many

    (一对多)单向:会产生中间表,此时可以用@onetoMany @Joincolumn(name=” “)避免产生中间表**,并且指定了外键的名字(别看 @joincolumn在一中写着,但它存在在多的那个表中)

  3. Many to One

    (多对一)单向:不产生中间表,但可以用@Joincolumn(name=” “)来指定生成外键的名字,外键在多的一方表中产生!

  4. Many to Many


可参考JPA实体关系映射

为什么要有实体关系映射

简化编程操作。把冗余的操作交给底层框架来处理。
例如,如果我要给一位新入学的学生添加一位新的老师。而这个老师又是新来的,在学生数据库与教师数据库中均不存在对应的数据。那么我需要先在教师数据库中保存新来的老师的数据,同时在学生数据库中保存新学生的数据,然后再给两者建立关联。
而如果我们使用了实体关系映射,我们只需要将该新教师实体交给该学生实体,然后保存该学生实体即可完成。

数据类型

  • String

    1
    2
    3
    4
    redis 127.0.0.1:6379> SET name "runoob"
    OK
    redis 127.0.0.1:6379> GET name
    "runoob"
  • Hash

    1
    2
    3
    4
    5
    6
    redis> HMSET myhash field1 "Hello" field2 "World"
    "OK"
    redis> HGET myhash field1
    "Hello"
    redis> HGET myhash field2
    "World"
  • List

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    redis 127.0.0.1:6379> lpush runoob redis
    (integer) 1
    redis 127.0.0.1:6379> lpush runoob mongodb
    (integer) 2
    redis 127.0.0.1:6379> lpush runoob rabitmq
    (integer) 3
    redis 127.0.0.1:6379> lrange runoob 0 10
    1) "rabitmq"
    2) "mongodb"
    3) "redis"
    redis 127.0.0.1:6379>
  • Set

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    redis 127.0.0.1:6379> sadd runoob redis
    (integer) 1
    redis 127.0.0.1:6379> sadd runoob mongodb
    (integer) 1
    redis 127.0.0.1:6379> sadd runoob rabitmq
    (integer) 1
    redis 127.0.0.1:6379> sadd runoob rabitmq
    (integer) 0
    redis 127.0.0.1:6379> smembers runoob

    1) "redis"
    2) "rabitmq"
    3) "mongodb"
  • zset(sorted set:有序集合)

    • Redis zset 和 set 一样也是string类型元素的集合,且不允许重复的成员。

      不同的是每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。zset的成员是唯一的,但分数(score)却可以重复。

    • 命令

      1
      zadd key score member 
    • 实例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      redis 127.0.0.1:6379> zadd runoob 0 redis
      (integer) 1
      redis 127.0.0.1:6379> zadd runoob 0 mongodb
      (integer) 1
      redis 127.0.0.1:6379> zadd runoob 0 rabitmq
      (integer) 1
      redis 127.0.0.1:6379> zadd runoob 0 rabitmq
      (integer) 0
      redis 127.0.0.1:6379> > ZRANGEBYSCORE runoob 0 1000
      1) "mongodb"
      2) "rabitmq"
      3) "redis"

操作

  • show all keys

    KEYS *

  • Delete All Keys In Redis

    1
    2
    3
    4
    5
    6
      Delete all keys from all Redis databases:
    `$ redis-cli FLUSHALL`
    Delete all keys of the currently selected Redis database:
    `$ redis-cli FLUSHDB`
    Delete all keys of the specified Redis database:
    `$ redis-cli -n <database_number> FLUSHDB`
  • 删除指定前缀的数据

    1
    2
    # 删除指定CCR866前缀的redis数据
    path/to/redis-cli -p 16379 -a Redis6379 -n 1 keys 'CCR866*' | xargs ./redis-cli -p 16379 -a Redis6379 -n 1 del
  • 在启动命令中添加 –raw,可以查看value的中文信息

问题解决

  • RedisConnectionFailureException

    1
    2
    3
    redis.conf中默认的是bind 127.0.0.1,需要将这段注释
    设置protected-mode no,因为如果是yes的话,只能进行本地访问。如果设置了密码和bind这个可以开启,如果没有设置,这个属性可以设置为no即可。
    daemonize yes表示后台运行
  • 需要安装gcc

  • make时,提示fatal error: jemalloc/jemalloc.h: No such file or directory

    1
    2
    3
    4
    5
    6
    解决:   
    cd src/deps
    make hiredis jemalloc linenoise lua geohash-int
    cd ..
    make
    sudo make install

    自定义配置redis server

    涉及到的目录或文件有

    1
    2
    3
    1.配置文件    /etc/redis/xxxx.conf
    2.日志、数据文件 /data/redis/xxxx
    3.启动脚本 /etc/init.d/redis_xxxx
  • 客户端启动时 redis-cli -p xxxx

高并发处理技术老司机带你玩RabbitMq实现性能倍增
链接:https://pan.baidu.com/s/1tdWyeXgXzbWsltY8NlhdaQ

密码:ripd

缓存那些事,缓存一致性问题爬坑记
链接:https://pan.baidu.com/s/10aX13k6GjIr7XUcrb6j-Pw

密码:f5kl

分布式事务处理你不得不听的踩坑故事-让你的代码经得起考验
链接:https://pan.baidu.com/s/1PeiCr0DYMI7x4LwGJktrOg

密码:phsp

大咖带你玩转分布式锁 Zookeeper篇
链接:https://pan.baidu.com/s/1Nh8mTrLNwtmh4hwU2khksg

密码:fznh

JRE JVM JDK

  • JRE: java run-time

Java is every where in browser, in mobile, in TV or in set-top boxes and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file require Java virtual machine JVM to execute it.

  • JVM: java virtual machine

Java Virtual Machine is get created when you run a java program using java command e.g. java HelloWorld. JVM is responsible for converting byte code into machine specific code

  • JDK: java development kit

JDK is also loosely referred as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program.

basic architecture of the JVM

Class Loader Sub System

1. Loading

  • loading the class file and store inside method area

  • Created object is not student object or customer object. It is a predefined class “Class” object that is presently in java.lang package.

  • For every loaded .class file, only one class “Class” object will be created by JVM, even though we are using that class multiple times in our program. Example,

2. Linking

  • verification

    This Byte Code Verifier is responsible to verify weather .class file is properly formatted or not, structurally correct or not, generated by valid compiler or not.

  • preparation

    allocate memory for class level static variables and assigned default values.

    E.g. For int —> 0, For double —> 0.0, For boolean —> false

  • Resolution

    It is the process of replacing all symbolic references used in our class with original direct references from method area.

  • Initialization

In Initialization activity, for class level static variables assigns original values and static blocks will be executed from top to bottom.

  • Types of class loaders in class loader subsystem
    • Bootstrap class loader/ Primordial class loader
    • Extension class loader
    • Application class loader/System class loader

3. Class loader sub system follows delegation hierarchy algorithm

  • Customized class loaderSometimes we may not satisfy with default class loader mechanism then we can go for Customized class loader. For example:

Various Memory Areas in JVM

1. Method Area

  • Inside method area class level binary data including static variables will be stored

  • Constant pools of a class will be stored inside method area.

  • Method area can be accessed by multiple threads simultaneously.

    All threads share the same method area, so access to the method area’s data structures must be designed to be thread-safe.

2. Heap Area

Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory.

These objects have global access and can be accessed from anywhere in the application.

This memory model is further broken into smaller parts called generations, these are:

  1. Young Generation – this is where all new objects are allocated and aged. A minor Garbage collection occurs when this fills up
  2. Old or Tenured Generation – this is where long surviving objects are stored. When objects are stored in the Young Generation, a threshold for the object’s age is set and when that threshold is reached, the object is moved to the old generation
  3. Permanent Generation – this consists of JVM metadata for the runtime classes and application methods
  • It’s accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation
  • If heap space is full, Java throws java.lang.OutOfMemoryError
  • Access to this memory is relatively slower than stack memory
  • This memory, in contrast to stack, isn’t automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage
  • Unlike stack, a heap isn’t threadsafe and needs to be guarded by properly synchronizing the code

  • Objects and corresponding instance variables will be stored in the heap area.

  • Every array in java is object only hence arrays also will be stored in the heap area.

  • Heap area can be access by multiple threads and hence the data stored in the heap area is not thread safe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Set Maximum and Minimum heap size
-Xmx
To set maximum heap size , i.e., maxMemory
java -Xmx512m HeapSpaceDemo
Here mx = maximum size
512m = 512 MB
HeapSpaceDemo = Java class name
-Xms
To set minimum heap size , i.e., total memory
java -Xms65m HeapSpaceDemo
Here ms = minimum size
65m = 65 MB
HeapSpaceDemo = Java class name
or, you can set a minimum maximum heap size at a time
java -Xms256m -Xmx1024m HeapSpaceDemo

3. Stack Memory

Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects that are in a heap, referred from the method.

1
2
3
Access to this memory is in Last-In-First-Out (LIFO) order. Whenever a new method is called, a new block on top of the stack is created which contains values specific to that method, like primitive variables and references to objects.

When the method finishes execution, it’s corresponding stack frame is flushed, the flow goes back to the calling method and space becomes available for the next method.
  • It grows and shrinks as new methods are called and returned respectively

  • Variables inside stack exist only as long as the method that created them is running

  • It’s automatically allocated and deallocated when method finishes execution

  • If this memory is full, Java throws java.lang.StackOverFlowError

  • Access to this memory is fast when compared to heap memory

  • This memory is threadsafe as each thread operates in its own stack


  • Local Variable Array

    • It contains all parameters and local variables of the method.

    • the occupied slot

  • Operand Stack

    • JVM uses operand stack as work space.

    • last-in first-out (LIFO)

    • how a Java virtual machine would add two local variables that contain ints and store the int result in a third local variable:

  • Frame Data

Stack Memory vs Heap Space

Parameter Stack Memory Heap Space
Application Stack is used in parts, one at a time during execution of a thread The entire application uses Heap space during runtime
Size Stack has size limits depending upon OS and is usually smaller then Heap There is no size limit on Heap
Storage Stores only primitive variables and references to objects that are created in Heap Space All the newly created objects are stored here
Order It is accessed using Last-in First-out (LIFO) memory allocation system This memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.
Life Stack memory only exists as long as the current method is running Heap space exists as long as the application runs
Efficiency Comparatively much faster to allocate when compared to heap Slower to allocate when compared to stack
Allocation/Deallocation This Memory is automatically allocated and deallocated when a method is called and returned respectively Heap space is allocated when new objects are created and deallocated by Gargabe Collector when they are no longer referenced

4. PC Registers(Program Counter Registers)

For every thread a separate PC register will be created at the time of thread creation. PC register contains address of current executing instruction. Once instruction execution completes automatically PC register will be incremented to hold address of next instruction. An “address” can be a native pointer or an offset from the beginning of a method’s byte codes.

5. Native Method Stacks

Here also for every Thread a separate run time stack will be created. It contains all the native methods used in the application. Native method means methods written in a language other than the Java programming language. In other words, it is a stack used to execute C/C++ codes invoked through JNI (Java Native Interface). According to the language, a C stack or C++ stack is created.

Execution Engine

1. Interpreter

It is responsible to read byte code and interpret into machine code (native code) and execute that machine code line by line.

2. JIT Compiler

The JIT compiler has been introduced to compensate for the disadvantages of the interpreter. The main purpose of JIT compiler is to improve the performance. Internally JIT compiler maintains a separate count for every method. Whenever JVM across any method call, first that method will be interpreted normally by the interpreter and JIT compiler increments the corresponding count variable.

  • Profiler which is the part of JIT compiler is responsible to identify Hotspot(Repeated Used Methods).

Java Native Interface(JNI)

JNI is acts as a bridge (Mediator) for java method calls and corresponding native libraries.

内存大小设置

  • 在命令行下用 java -Xmx1200m -XX:Max Perm Size=60m -version 命令来进行测试,然后逐渐的增大XXXX的值,如果执行正常就表示指定的内存大小可用,否则会打印错误信息。
    最后得到的虚拟机实际分配到的
    总内存大小=堆内存+非堆内存
    1200m:为堆内存大小,如果不指定后者参数则有最大数限制,网上很多文章认为这就是JVM内存, -Xmx为设置最大堆内存
    60m: 为非堆内存大小, -XX: Max PermSize实为 永久域内存,在堆内存之外,属于非堆内存部分,jdk1.5我测了好像默认为62m,即得到非堆部分默认内存)

进程内存

查看进程对象大小

  • jmap -histo 进程id

    1
    jmap -histo 123456 | head -n15

查看内存分布及回收情况

  • jstat -gc 进程id 毫秒

    1
    jstat -gc 1692 5000

    S0C: Young Generation第一个survivor space的内存大小 (kB).
    S1C: Young Generation第二个survivor space的内存大小 (kB).
    S0U: Young Generation第一个Survivor space当前已使用的内存大小 (kB).
    S1U: Young Generation第二个Survivor space当前已经使用的内存大小 (kB).
    EC: Young Generation中eden space的内存大小 (kB).
    EU: Young Generation中Eden space当前已使用的内存大小 (kB).
    OC: Old Generation的内存大小 (kB).
    OU: Old Generation当前已使用的内存大小 (kB).
    MC: Permanent Generation的内存大小 (kB)
    MU: Permanent Generation当前已使用的内存大小 (kB).
    YGC: 从启动到采样时Young Generation GC的次数
    YGCT: 从启动到采样时Young Generation GC所用的时间 (s).
    FGC: 从启动到采样时Old Generation GC的次数.
    FGCT: 从启动到采样时Old Generation GC所用的时间 (s).
    GCT: 从启动到采样时GC所用的总时间 (s).

查看堆栈占用

  • jmap -heap 进程id

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    S0: 新生代中Survivor space 0区已使用空间的百分比
    S1: 新生代中Survivor space 1区已使用空间的百分比
    E :新生代已使用空间的百分比 Eden space
    O: 老年代已使用空间的百分比(P: 永久带已使用空间的百分比)

    M: 元空间使用百分比
    CCS: 压缩类空间利用率为百分比
    YGC: YGC次数
    YGCT: 年轻一代垃圾收集时间
    FGC: FGC次数.
    FGCT: 完全垃圾收集时间
    GCT: 垃圾回收总时间

命令介绍

  1. mvn compile 编译,将Java 源程序编译成 class 字节码文件。
  2. mvn test 测试,并生成测试报告
  3. mvn clean 将以前编译得到的旧的 class 字节码文件删除
  4. mvn pakage 打包,动态 web工程打 war包,Java工程打 jar 包。
  5. mvn install 将项目生成 jar 包放在仓库中,以便别的模块调用
  6. Maven的几个常用plugin

tomcat项目的部署

maven多项目之间相互引用

  • 应该在父目录下进行maven install操作,会自动生成子模块的jar或war包。

  • 解决maven无法加载本地lib/下的jar包问题(程序包XXX不存在)

    • 原因

      若该程序包是第三方的jar,解决方案是让maven既加载maven库中的jar包,又要加载本地WEB-INF/lib下的jar包。

    • 解决

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.6.0</version>
      <configuration>
      <source>1.8</source>
      <target>1.8</target>
      <encoding>UTF-8</encoding>
      <compilerArguments>
      <extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib</extdirs>
      </compilerArguments>
      </configuration>
      </plugin>

创建本地引用包

1.直接引用本地jar

将jar放在项目中,例如web项目就放在 webapp/WEB-INF/lib下面
然后再pom.xml中添加jar的依赖:

1
2
3
4
5
6
7
<dependency>
<groupId>myjar</groupId>
<artifactId>myjar</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/webapp/WEB-INF/lib/myjar-1.0.0.jar</systemPath>
</dependency>

2.安装到本地仓库

1
2
3
4
5
6
7
8
mvn install:install-file -Dfile=xxx.jar -DgroupId=xx.xxx.xx -DartifactId=xx -Dversion=xx -Dpackaging=jar

参数说明:
-DgroupId:对应dependency的groupId
-DartifactId:对应dependency的artifactId
-Dversion:对应dependency中的version
-Dpackaging:安装的类型,jar或者pom
-Dfile:要安装的jar文件的路径

scope

  • compile
    默认就是compile,什么都不配置也就是意味着compile。compile表示被依赖项目需要参与当前项目的编译,当然后续的测试,运行周期也参与其中,是一个比较强的依赖。打包的时候通常需要包含进去。

  • test
    scope为test表示依赖项目仅仅参与测试相关的工作,包括测试代码的编译,执行。比较典型的如junit。

  • runntime
    runntime表示被依赖项目无需参与项目的编译,不过后期的测试和运行周期需要其参与。与compile相比,跳过编译而已,说实话在终端的项目(非开源,企业内部系统)中,和compile区别不是很大。比较常见的如JSR×××的实现,对应的API jar是compile的,具体实现是runtime的,compile只需要知道接口就足够了。oracle jdbc驱动架包就是一个很好的例子,一般scope为runntime。另外runntime的依赖通常和optional搭配使用,optional为true。我可以用A实现,也可以用B实现。

  • provided
    provided意味着打包的时候可以不用包进去,别的设施(Web Container)会提供。事实上该依赖理论上可以参与编译,测试,运行等周期。相当于compile,但是在打包阶段做了exclude的动作。

  • system
    从参与度来说,和provided相同,不过被依赖项不会从maven仓库抓,而是从本地文件系统拿,一定需要配合systemPath属性使用

依赖传递原则

几乎所有的Jar包冲突都和依赖传递原则有关,所以我们先说Maven中的依赖传递原则:

最短路径优先原则

假如引入了2个Jar包A和B,都传递依赖了Z这个Jar包:

A -> X -> Y -> Z(2.5)
B -> X -> Z(2.0)

那其实最终生效的是Z(2.0)这个版本。因为他的路径更加短。如果我本地引用了Z(3.0)的包,那生效的就是3.0的版本。一样的道理。

最先声明优先原则

如果路径长短一样,优先选最先声明的那个。

A -> Z(3.0)
B -> Z(2.5)

这里A最先声明,所以传递过来的Z选择用3.0版本的。

引用本地jar包依赖

  1. jar包放入项目指定位置 ie:${project.basedir}/src/main/resources/lib/xxx.jar

  2. pom文件引入依赖

    1
    2
    3
    4
    5
    6
    7
    <dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>sdk.core</artifactId>
    <version>3.3.1</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/src/main/resources/lib/xxx.jar</systemPath>
    </dependency>

    systemPath这个路径是jar包的路径。${project.basedir}只是一个系统自己的常量。

  3. 在将项目用Maven打包是需要在 标签中加入:

    1
    2
    3
    4
    5
    6
    7
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
    <includeSystemScope>true</includeSystemScope>
    </configuration>
    </plugin>

init project

1
mvn archetype:generate -DgroupId=brook.hbase -DartifactId=hbase-client -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

命令启动springboot

1
mvn spring-boot:run

add git commit info to jar package

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>2.2.4</version>
<executions>
<execution>
<id>get-the-git-infos</id>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration>
<dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
<prefix>git</prefix>
<verbose>false</verbose>
<generateGitPropertiesFile>true</generateGitPropertiesFile
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
<format>json</format>
<gitDescribe>
<skip>false</skip>
<always>false</always>
<dirty>-dirty</dirty>
</gitDescribe>
</configuration>
</plugin>

生成的git.properties会在jar包位置 BOOT-INF/classes/git.properties

相关问题

Creational Design Patterns

These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case.

Singleton

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

  • different approaches to implement:

    • Private constructor to restrict instantiation of the class from other classes.
    • Private static variable of the same class that is the only instance of the class.
    • Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
  • design concerns with the implementation

    • Eager initialization
    • Static block initialization
    • Lazy Initialization
    • Thread Safe Singleton
    • Bill Pugh Singleton Implementation
    • Using Reflection to destroy Singleton Pattern
    • Enum Singleton
    • Serialization and Singleton
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    //SingleObject.java
    public class SingleObject {

    //create an object of SingleObject
    private static SingleObject instance = new SingleObject();

    //make the constructor private so that this class cannot be
    //instantiated
    private SingleObject(){}

    //Get the only object available
    public static SingleObject getInstance(){
    return instance;
    }

    public void showMessage(){
    System.out.println("Hello World!");
    }
    }

    //SingletonPatternDemo.java
    public class SingletonPatternDemo {
    public static void main(String[] args) {

    //illegal construct
    //Compile Time Error: The constructor SingleObject() is not visible
    //SingleObject object = new SingleObject();

    //Get the only object available
    SingleObject object = SingleObject.getInstance();

    //show the message
    object.showMessage();
    }
    }

Factory

  • Factory design pattern provides approach to code for interface rather than implementation.
  • Factory pattern removes the instantiation of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend. For example, we can easily change PC class implementation because client program is unaware of this.
  • Factory pattern provides abstraction between implementation and client classes through inheritance.

Abstract Factory

  • Abstract Factory design pattern provides approach to code for interface rather than implementation.
  • Abstract Factory pattern is “factory of factories” and can be easily extended to accommodate more products, for example we can add another sub-class Laptop and a factory LaptopFactory.
  • Abstract Factory pattern is robust and avoid conditional logic of Factory pattern.

Builder

  • Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.

Prototype

  • Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing.Prototype pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Prototype design pattern uses java cloning to copy the object.

Structural Design Patterns

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.

Adapter

  • Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.

Composite

  • Composite design pattern is used when we have to represent a part-whole hierarchy.

Proxy

  • Proxy design pattern common uses are to control access or to provide a wrapper implementation for better performance.

Flyweight

  • Use sharing to support large numbers of fine-grained objects efficiently

Facade

  • Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.

Bridge

  • Decouple an abstraction from its implementation so that the two can vary independently.

Decorator

  • Decorator design pattern is helpful in providing runtime modification abilities and hence more flexible. Its easy to maintain and extend when the number of choices are more.
  • The disadvantage of decorator design pattern is that it uses a lot of similar kind of objects (decorators).

Behavioral Design Patterns

These design patterns are specifically concerned with communication between objects.

Template Method

  • Template method should consists of certain steps whose order is fixed and for some of the methods, implementation differs from base class to subclass. Template method should be final.
  • Most of the times, subclasses calls methods from super class but in template pattern, superclass template method calls methods from subclasses, this is known as Hollywood Principle – “don’t call us, we’ll call you.”.
  • Methods in base class with default implementation are referred as Hooks and they are intended to be overridden by subclasses, if you want some of the methods to be not overridden, you can make them final, for example in our case we can make buildFoundation() method final because if we don’t want subclasses to override it.

Media

  • Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another.

Architectural

Business Object

A business object is a normal class which has a normal business logic.

Aspect

An aspect is a modularization of a concern that cuts across multiple classes.

JoinPoint

A Joinpoint is a point during the execution of a program, such as execution of a method or the handling of an exception.

In Spring AOP, a JoinPoint always represents a method execution.

Pointcut

A Pointcut is a predicate that helps match an Advice to be applied by an Aspect at a particular JoinPoint.

The Advice is often associated with a Pointcut expression and runs at any Joinpoint matched by the Pointcut.

Advice

An advice is an action taken by an aspect at a particular Joinpoint. Different types of advice include “around,” “before” and “after” advice.

In Spring, an Advice is modeled as an interceptor, maintaining a chain of interceptors around the Joinpoint.


Example:Wiring Business Object and Aspect

  • Business Object

    1
    2
    3
    4
    5
    public class SampleAdder {
    public int add(int a, int b) {
    return a + b;
    }
    }
  • a simple Aspect

    Unified logging can be an example of such cross-cutting concern:

    1
    2
    3
    4
    5
    6
    public class AdderAfterReturnAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public void afterReturn(Object returnValue) throws Throwable {
    logger.info("value return was {}", returnValue);
    }
    }
  • config excerpt

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <bean id="sampleAdder" class="org.xxx.SampleAdder" />
    <bean id="doAfterReturningAspect"
    class="org.xxx.AdderAfterReturnAspect" />
    <aop:config>
    <aop:aspect id="aspects" ref="doAfterReturningAspect">
    <aop:pointcut id="pointCutAfterReturning" expression=
    "execution(* org.xxx.SampleAdder+.*(..))"/>
    <aop:after-returning method="afterReturn"
    returning="returnValue" pointcut-ref="pointCutAfterReturning"/>
    </aop:aspect>
    </aop:config>

依赖注入DI有助于应用对象之间的解耦,而AOP可以实现横切关注点与它们所影响的对象之间的解耦

  • 通知Advice

    切面的工作被称为通知,通知定义了切面是什么以及何时使用。

    • 前置通知(Before):在目标方法被调用之前调用通知功能
    • 后置通知(After):在目标方法完成之后调用通知,此时不会关心方法的输出
    • 返回通知(After-returning):在目标方法成功执行之后调用通知
    • 异常通知(After-throwing):在目标方法抛出异常后调用通知
    • 环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。
  • 连接点Join point

    连接点是应用程序的点,可供插入切面

    我理解的是程序的某处,或者任意一处都可以称作为连接点

  • 切点Pointcut

    切点有助于缩小切面所通知的连接点的范围

    如果Advice定义了切面的what和when,那么pointcut就定义了where

  • 切面Aspect

    Aspect是Advice和Pointcut的结合