java Back end 5 Year experience and technical summary
Graduation has been 5 Over the year , this 5 Special thanks to the technical management staff for their respect during the year , And the help of colleagues , I learned a lot . this 5 Through some detours in the year , There are also some problems , I've also suffered from being a developer and being a firefighter for system maintenance and release . So I decided to sort out what I had learned , Let's share it with you .
After a year, I realized that there were many misunderstandings before , such as ：
Preference for collection , Often collect all kinds of information, video jam hard disk , And then contentedly watch the capacity do not act .
No emphasis on foundation , I always feel that many basic things don't need to be looked at again , In fact, there are many things I don't understand , In terms of computer programs, there must be a reason for any result , Don't just know the principle , That's from the processing plant . Now? ide It's so convenient to look at the code ,ctrl+ Click to enter JDK View implementation details .
reach for what is beyond one 's grasp , In the case of weak Computer Foundation , Always want to do the structure , Get distributed , Big data and so on .
No emphasis on Performance , Only the function can be realized ,sql Query can be optimized , Is there an algorithm , Do you want to clear large objects .
No emphasis on scalability , Close coupling between modules , Common methods are not extracted into tool classes , Call relationship confusion and other issues .
PS： If you also encounter many problems in the process of study or work , You can check my bulletin board , Answer as you ask , And some of the things I've been working on these days Java Learning manual , Interview questions , development tool ,PDF Document book tutorial , If you need it, you can share it for free .
This article does not focus on these , So only a small part of , Let's get to the point .
2. elements of grammar
2.1 Java Class initialization order
This is the order of class initialization in all cases , If there is no definition in the actual class, skip ： Parent static variables —— Parent static code block —— Subclass static code block —— The parent class is not a static variable —— Parent class non static code block —— Parent constructor —— Subclass nonstatic variables —— Subclass non static code block —— Subclass constructor
2.2 Value passing and reference passing
Maybe a lot of people are dismissive of it , I thought I had been working for a year , Not familiar with this ？ But this is not the case ,JDK Are you familiar with everything in Chinese ？ Start with the simplest example , You think after the code in the figure below has been executed fatherList What is the element in ？
This is a basic example of value passing and reference passing , You think it's easy , I'm ready for a challenge , So look at the following ,StringBuffer Well understood. , But when you do it again, you find that the output is not the same as expected ？String Isn't it a reference type , How could this happen ？ If you can't understand , So please have a look String Implementation of the source code , Understand the implementation principle of its allocation in memory .
2.3 Use of collections
This part is used by almost everyone , And we are all familiar with it . The figure below is from the Internet , For your review . But the use of the characteristics of the set for clever combination can solve many complex optimization problems .Set Non repeatability ,List The order of ,Map The key/value pair ,SortSet/SortMap The order of , I have a lot of complicated business in my work, which I use skillfully , Involving company confidential information , I won't post the code . The longer you work, the more you discover it and the more ingenious .
2.3 exception handling
1. Look at try、catch、finally Very easy to , If combined with transaction propagation , It becomes extremely complicated .
2.finally It doesn't have to be enforced ,return stay catch/finally Medium treatment （ I suggest you try it yourself ）.
3.catch You can continue to throw custom exceptions in （ And pass the exception step by step to the control layer , Using facet grabbing to encapsulate exceptions , Back to the caller ）.
2.4 Object oriented idea
First, object oriented , We all know the abstract 、 encapsulation 、 Inherit 、 Polymorphism . But how much do you know from your actual work experience , How to use estimates skillfully in a project, let alone .
Common opportunities each need to use to build a base class , For example, each control layer method may have to pass security Get a login user id, It is used to operate different data according to different users , You can abstract an application layer base class , Implement access id Of protect Method . Empathy DAO Layer can use generics to extract a base class containing addition, deletion, modification and query .
Polymorphic Override： The reference variable of the base class can not only point to the instance object of the base class , You can also point to an instance object of its subclass , If you point to an instance object of a subclass , The method it calls should be the method of the running object . It's very common to use in policy mode .
When it comes to object orientation , It's inevitable to talk about design patterns , At work , A technology guru wrote a similar strategy model （ More complicated ）, Very clever solution to all kinds of business, the same method , And realized the order 、 The repair order 、 Business decoupling , I admire it very much . I think a lot of interviews will ask about the single case model , Don't understand the suggestion to have a look .
3.1 Thread safety
This is a trite question , But it's a problem bug High incidence area . Thread synchronization does not need to be written separately , I think everyone knows , Not very familiar with the proposal of Baidu .
3.1.1 Thread safety problem
1. If there is synchronization in the code , Special attention should be paid to sharing variables （ This one is generally aware of ）
2 Multiple operations can modify the same data in the data table .（ This is easy to ignore , Business A Possible operation table a, Business B You can also manipulate tables a, Business A、B Even in different modules and methods , It can also cause thread safety problems . If a person visits a business, for example A Interface , Another person visits the business B Interface , stay web Each business request is processed by a separate thread , There will be thread safety issues ）.
3. Unsafe type use , for example StringBuffer、StringBuild,HashTable、HashMap etc. . I've met people at work for Cycle are list Of remove, Although the compiler does not report errors , The program can run , But it turns out that .
4.Spring Of bean The default is singleton , Be careful if you have class variables （ Generally, no one is at the control level 、 The business layer 、DAO Class variable , In other words, the suggestion is final type , Log for example log,gson etc. ）.
5. Multiple systems share databases , This is actually similar to a distributed system
User repeated submission （ Even if there are restrictions on reading from the database in the code, it can't solve the problem ）
3.1.2 Thread safety solution
Use secure types where synchronization is needed .
JDK Locking mechanism ,lock、tryLock,synchronized,wait、notify、notifyAll etc.
Concurrent Concurrent toolkit , In dealing with some problems , Who knows . It is highly recommended to check the source code ！
Data table locking .（ Unless a table has very low access frequency , Otherwise, it is not recommended to use ）
Involving distributed , Using middleware technology such as zookeeper Etc .
Asynchronous usage scenarios do not affect the main thread , And slow response business . for example IO operation , Third party service （ SMS verification code 、app push 、 Cloud storage upload, etc ）.
If there are many asynchronous tasks , You need to use a task queue , Task queues can be implemented at the code level , You can also use redis（ The advantage is so obvious ）.
3.3 Multithreaded communication
There are many articles in this field , I'm not going to go into details here .
1. How to share variables （ Shared files 、 Global variables , Semaphore mechanism, etc ）
2. Message queuing
3. Busy etc. , Locking mechanism
3.4 Multithreaded implementation
1. Integrate Thread class , rewrite （ The rewriting here refers to override）run Method , call start Method execution .
2. Realization Runable Interface , Realization run Method , With Runable Instance creation thread object .
3. Realization Callable Interface , Realization call Method ,FutureTask packing callable Interface ,FutureTask objects creating thread object , Asynchronous operation , Anonymous inner classes are recommended , Easy to read and use .
What's more, it should be noted that ：
1. understand thread Of join Method ;
2. Don't think volitate It's thread safe （ If you don't understand the reason, go and see jvm Runtime memory allocation strategy ）;
3.sleep It's not guaranteed to be available immediately after the time slice is over cpu.
4.ThreadLocal Ability to maintain variable copies for each thread , It is often used to trade space for time in multithreading .
4. Open source framework
Believe in each java Programmers are familiar with all this , No more details here .
The main points to be explained are as follows ：
1.hibernate First level cache （ built-in session cache ）, Second level cache （ Can be assembled sessionFactory cache ）, L2 caching can cause concurrency problems .
2.hibernate Understanding of delayed loading principle .
3.hibernate Of get、load Method ,sava、persist、savaOrUpdate Method difference
4.session The association relationship is rebuilt, but it is not synchronized and updated with the database
5.hibernate session Connections ：detached object 、persistent object
6.Spring data Integrate , Annotation mode configuration properties and entities .
7.mybatis plug-in unit .
8. Paging query （ database ）.
9. Connection pool technology
4.2 Spring IOC
4.1.1 Spring bean
1.bean Inject Annotations are easy to read , Quote a third party （ Database connection , Database connection pool ,JedisPool etc. ） In profile mode .
2. bean Scope ：Singleton,prototype,request,session,global session
3.bean Life cycle : As shown in the figure below （ The picture comes from the Internet ）：
4.3 Spring AOP
Basic concepts ： concerns 、 section Aspect、 The breakthrough point pointcut、 Connection point joinpoint、 notice advice、 Weaving weave、 introduce introduction.
Spring AOP Support 5 Medium type notification , Namely MethodBeforeAdvice、AfterReturningAdvice、ThrowsAdvice、MethodInterceptor、IntroductionInterceptor（ Make complaints about the name too long. ）
The implementation is as follows :
1. Agent based AOP
2. be based on @Aspect Annotation driven facets .（ Strongly recommend ： Good readability , Easy maintenance , Easy to expand , Fast development ）
3. pure POJO section .
4. Injection type Aspect section .
4.4 Srping Business
4.4.1 Communication affairs
Concept ： Some operations need to be atomic , If something goes wrong in the middle , Transaction rollback is required . If a transaction rolls back , Then, what action is taken by the transaction in the method calling the transaction , It's business communication .
Transaction propagation properties ：
1. PROPAGATION_REQUIRED– Support current transaction , If there is no current transaction , Just create a new transaction . This is the most common choice .
2. PROPAGATION_SUPPORTS– Support current transaction , If there is no current transaction , Just in a non transactional way .
3. PROPAGATION_MANDATORY– Support current transaction , If there is no current transaction , Throw an exception .
4. PROPAGATION_REQUIRES_NEW– New transaction , If there are currently transactions , Suspend current transaction .
5. PROPAGATION_NOT_SUPPORTED– Perform operations in a non transactional way , If there are currently transactions , Suspend the current transaction .
6. PROPAGATION_NEVER– To execute in a non transactional manner , If there are currently transactions , Throw an exception .
Transaction isolation level ：
1. ISOLATION_DEFAULT： This is a PlatfromTransactionManager Default isolation level , Use the database's default transaction isolation level . The other four are with JDBC The isolation level of corresponds to
2. ISOLATION_READ_UNCOMMITTED： This is the lowest level of isolation for transactions , Allow another transaction to see the uncommitted data of this transaction . This isolation level produces dirty reads , Do not repeat reading and phantom reading .
3. ISOLATION_READ_COMMITTED： Ensure that the data modified by one transaction can only be read by another transaction after it is submitted . Another transaction cannot read uncommitted data of the transaction
4. ISOLATION_REPEATABLE_READ： This transaction isolation level prevents dirty reads , It can't be read repeatedly . But there may be phantom reading . In addition to ensuring that one transaction cannot read uncommitted data of another transaction , It also ensures to avoid the following situations ( It can't be read repeatedly ).
5. ISOLATION_SERIALIZABLE This is the most expensive but reliable level of transaction isolation . Transactions are processed as sequential execution . In addition to preventing dirty reading , Do not read outside again , It also avoids phantom reading .
4.5 other Spring Technology stack
spring boot Lightweight startup framework
spring security User authority management , According to roles and users , Realization UserDetailsService, User defined permission management .
spring task Code level timing task , Annotation mode , It is very convenient to use . It should be noted that , If an exception occurs in a scheduled task and it is not handled , It will cause the next scheduled task to fail . If the tasks are independent of each other , It's easy to use try,catch Surround （ I have suffered from this before ）.
spring data Defining entities by annotation , Properties, etc
spring mvc Simple and clear mvc frame .url Pass value 、 Array pass value 、 Object value transfer 、 Object array, etc , Upload / You need to pay attention to the type of download file .
spring restful Pay attention to naming , It's very strict with naming .
spring shell Command line mode to execute commands , Put out the fire 、 It is very convenient to import and export data 、 Make reports .
5. Web Basics
5.1 web Container start up
1.web.xml Loading order : listener -> filter -> servlet
2.webt Container startup process ,java Novices are afraid of configuration files , Understanding these will help you familiarize yourself with the configuration files
Servlet Receive request return response , ancestral web Business processing class .
Interceptor Interceptor , Can achieve HandlerInterceptor Interface custom interceptor , In the log 、 Permission check 、 Performance monitoring 、 General behavior and other scenarios , The essence is AOP.
Listener Monitor It is often used to count the number of people online and other vertical functions .
Filter filter Change before requesting the interface to handle business requset, Change after business processing before responding to users response. If some data is not encrypted , It's easy to add filter cheat .
5.3 web Project structure
5.3.1 mvn structure
Master several common mvn Project structure ,mvn Can be generated automatically , No more details here .
5.3.2 mvn Package management
1. Version numbers should be as few as possible in one file for easy management .
2.spring milestone Package solution spring Package conflict issues .
3.mvn dependency:tree Command to analyze all package dependencies , For the conflict in the pom In file Surrounded
5.3.3 version control
2. Code conflict resolution
3. Branch management .
After a stable version goes online , If we develop new functions on this basis , Be sure to create a new branch , Commit code on a new branch , Finally, merge branches when the new version is released . Modify operating environment bug Switch to the main branch to modify
5.4 Http request
5.4.1 Request method
post、get、put、head、delete、copy、move、connect、link、patch, The most commonly used is the front 4、5 individual .
5.4.2 Request header , Status code
Common request headers are Accept（ Download files will be specially used ）、Accept-Charset（ Set up utf-8 Character set ）、Content-Type（json Other configuration ） etc.
Common response headers are Content-Type、Content-Type、Content-Length etc. , Partial front end , No more details .
6. System architecture
Not much contact , At present, only the master-slave backup of the server is used .Nginx Reverse proxy configuration .
Multiple projects nginx To configure
Spring Mvc use json Data to interact , To configure json The conversion servlet.
Encapsulate the return value
Customize RunEnvironmentException（ Status code , reason ）, Cover the original Exception, section ExceptionHandler Grab Exception And encapsulated in the return value （ Loose coupling between front and rear ends ）
Annoying user repetition （ Continuous quick click ） Submit questions , The front-end restriction is a temporary cure, not a root cause ; For the back end sessonid Implemented on cut , Front end storage is needed , Add to all request data sessionId. Last use jedis Storage in , Use the interface name + User name as key, According to the different interfaces, it can be used for different key The time can be set individually , Not only does it ensure that the problem is repeatedly submitted , It also avoids the problem of malicious requests , At the same time, you can customize the request interval .（ Worry at the beginning of the period redis Cache read / write time delay results in limit invalidation , Later, I found that I was worried , For the average small system , Performance test , Found that even if the frequency of requests increased again 100 Being will not cause the restriction to fail ）
testNg unit testing 、 Performance testing , Coverage test .
Face to face management date 、 jurisdiction . Cache, etc .
1.Redis Of java library Jedis.
Jedispool To configure .
The task queue is used in the project 、 cache .
2. neo4j Graph database
Dealing with social interaction 、 recommend
8. Server side
linux Operating system familiar with centos For example ：
Common simple commands ：ssh、vim、scp、ps、gerp、sed、awk、cat、tail,df、top,shell、chmod、sh、tar、find、wc、ln、|
Directory structure details :/etc/、~/、/usr/、/dev/、/home/、/etc/init.d/
Server side ：jdk、tomcat、nginx、mysql、jedis、neo4j Startup and configuration （ Specifically, the damned firewall ,nginx You can't access it since it's started , I can't find out why in the afternoon , Finally, it turns out that there is a firewall problem ）
Monitor server status （cpu, disk , Memory ）, location pid, Log view
nginx Load balancing 、 Reverse proxy 、 To configure
* * Automated Deployment scripts
Simple shell Script writing , Avoid a lot of human labor .
The monitoring system , Code throwing fatal Abnormal automatic email , System indicators continue to be high, automatic email .
9. Database correlation
10. Third party interface docking
10.1 Payment interface
There are many wechat payment pits , It took nearly two weeks to complete wechat payment . There are too many places to configure in the wechat background .
The Alipay payment module is used only 2 It's just a matter of days .
10.2 Push interface
Define... For the user tag、 Definition alias, Note that when the data is updated, it needs to be updated synchronously tag、 to update alias. If it's not implemented asynchronously （ User experience is a good card ）
10.3 Cloud storage
A large number of files uploaded to the cloud （ Qiniuyun ）, Pay attention to creating bucket
10.4 SMS verification
Very simple third party interface , Introduce dependencies , Just call it directly . You need to set up templates in the third-party background , Pay attention to limiting the number of user visits .
It's very simple, small function , Tool class .
Time is limited , At present, we should write so many technology stacks first . For code writing and 、 Algorithmic skills , Take time to share .