Summary of simulated interview questions

Posted by prion on Sat, 19 Feb 2022 17:53:19 +0100

Summary of simulated interview questions 

First round interview questions


Summary of simulated interview questions

First round interview questions

1, Describe the characteristics of the transaction ACID in the database.

2, What is springboot? Which version does your company use?

Second round interview questions

The third round of interview questions

The fourth round of interview questions

The fifth round of interview

1. Dead letter, delay and retry queue

8. Microservices

9. Problems of Java lock mechanism

Inster written test:

Softcom power telephone interview:

Duofei network technology:

Beijing alangre:

Palm edge information technology:

Zhongke soft

Duanmu company


1, Describe the characteristics of the transaction ACID in the database.

Atomicity: all operations in a transaction either succeed or fail.
Consistency: the integrity of data before and after a transaction must be consistent.
Isolation: multiple concurrent transactions are isolated from each other and do not interfere with each other.
Persistence: after the transaction is committed, the data is permanently changed.


2, What is springboot? Which version does your company use?

SpringBoot yes Spring Introduced to solve the redundancy of traditional framework configuration files,Complex assembly based on components Maven Solutions for,It aims to quickly build a single micro service.
Version number: 2.1.6


3, What is redis?

Redis It is completely open source and free of charge BSD The protocol is a high-performance protocol key-value database


4, How to understand the relationship among Eureka, provider and consumer in spring cloud microservice project?

eureka: Provide services registered at discovery
provider:The service provider method registers itself with eureka,Let consumers find
consumer:Service consumer from eureka Get the list of registered services and be able to consume services


5, What is the default mysql storage engine?

Mysql stay V5.1 Previously, the default storage engine was MyISAM;After that, the default storage engine is InnoDB. 

MyISAM Transaction not supported, InnoDB Support transactions.

MySIAM Foreign keys are not supported, InnoDB Support foreign keys,

MySIAM Support full-text indexing, InnoDB Full text indexing is not supported.


6, What is cross domain?

To understand cross domain, first talk about homology strategy. The so-called homology means that the domain name, protocol and port are the same, and if one is different, it is cross domain.


7, What is a token?

Token It is a string generated by the server as a token for the client to make a request.
After the first login, the server generates a Token Then put this Token Return to the client,
In the future, the client only needs to bring this Token You can come to request data without bringing your user name and password again.


8, What is RESTful?

first rest It's a kind of API Mode, often with JSON Format writing. accord with rest An application or design that constrains styles and principles is RESTful. 


9, What problems does spring cloud solve?

Complexity associated with distributed systems 
Ability to handle service discovery
Solve redundancy problems 
load balance  
Reduce performance issues 


10, What is fusing in microservices? What is service degradation?

The function of service fusing is to temporarily stop calling a service when it is unavailable or the response times out in order to prevent the avalanche of the whole system.       
Service degradation is to prevent overload or slow response of some functions (business scenarios), temporarily abandon the requests for some non core interfaces and data, and directly return a prepared interface fallback(Fallback) error handling information.


11, What are the advantages and disadvantages of microservices?


Because it is easier to develop and maintain a specific service. At the same time, it is convenient to maintain.
A single service starts quickly: a single service will start quickly without a lot of code.
Easy to scale: if there are three service ABC in the system and the traffic of service B is relatively large, we can deploy service B cluster.

The operation and maintenance requirements are relatively high: there was a war package before. Now there are many services in a system. Each service corresponds to a war package, which will become very troublesome to maintain.
Increasing technical complexity: microservices will bring a series of problems, such as transaction problems, Session consistency problems, lock problems, etc.


12, How do microservices communicate independently?

Synchronous communication: dobbo adopt RPC Remote procedure call springcloud adopt REST Interface json Call, etc.
Asynchronous: message queue, such as: RabbitMq,ActiveMq,Kafka Wait.


13, What are the differences between spring cloud and Dubbo?

First, they are all distributed management frameworks.
    dubbo It is binary transmission, which will occupy less bandwidth. SpringCloud yes http For transmission, the bandwidth will be a little more and used at the same time http The protocol will generally use JSON Message consumption will be greater.
    SpringCloud The interface protocol agreement is relatively loose, and strong administrative measures are needed to limit the disorderly upgrading of the interface.
The biggest difference:
    Spring Cloud Abandoned Dubbo of RPC Communication is based on HTTP of REST Way.


14, What is the relationship between SpringBoot and SpringCloud?

SpringBoot: Focus on the rapid and convenient development of individual micro services (focusing on micro);
SpringCloud: The overall micro service coordination governance framework will SpringBoot The developed individual micro services are combined and managed (focusing on the macro);
SpringBoot Can leave SpringCloud Independent use, but SpringCloud You can't leave SpringBoot,It belongs to dependency.


15, What's the difference between eureka and zookeeper?

eureka and zookeeper Can provide the functions of service registration and discovery, zookeeper yes CP Principle, strong consistency and partition fault tolerance. eureka yes AP Principle availability and partition fault tolerance.
zookeeper When the master node fails, zk It takes too long to re select the master node in the remaining nodes. Although it can be restored eventually, the service will be unavailable during the selection of the master node, which is intolerable.
eureka All nodes are equal. If one node hangs up, other nodes will still ensure normal service.


16, What is mycat? What are the segmentation rules of your company's sub database and sub table?

Mycat is a database middleware based on MySQL, which is used to coordinate the segmented database so that it can be managed uniformly.

Partition rule: module partition PartitionByMode


17, What is a collection?

The collection has two parent interfaces, one collection,One Map;
and collection There are two sub interfaces, one List,One Set;
List There are two common implementation classes ArrayList,LinkedList;
Set There are two common implementation classes HashSet,TreeSet;
Map There are two common implementation classes HashMap,HashTable. 


18, What is dubbo?

Dubbo and spring cloud are commonly used frameworks in distributed services. Different from cloud, Dubbo is based on RPC Protocol. It provides three core functions: interface oriented remote method invocation,

Intelligent fault tolerance and load balancing, and automatic service registration and discovery.


19, What is spring?

Spring Is an open source lightweight Java Development framework. Is a simplified application development.
stay spring Before coming out, service Layer call dao All layers are used new The way, in spring After coming out, service Layer and to dao Layers will be placed in spring Container management,

This is spring The first feature we call IOC,Control reversal.
spring There is another feature that we call AOP,In vernacular, the so-called "face to face" means that special people do special things.

In the project, many public or repeatedly called modules can be extracted and used AOP Features, such as log module.



Second round interview questions

1, What are the development steps of SSM?



1. Front end controller DispatcherServlet

2. Filter characterencoding filter



1. Scan package < context: component scan base package = "CN" / >

2.mvc driver < MVC: annotation driven / >

3. Transaction driven < TX: annotation driven transaction manager = "txmanager" / >

4. Configure data source


6. Configuration transactions

7. Data mapper

8. View parser


2, Design a permission module?

The authority module is the security system of the database, which determines who can use, who has authority and who has authority user,role,permission Table, through user-role,role-permission Association table (code table),

Assign permissions to roles, and roles issue permissions to users.


3, What is docker?

Docker Is an open source application container engine, which allows developers to package their applications and dependency packages into a portable image, and then publish them to any popular application Linux or Windows On the machine,

Virtualization can also be achieved. Containers are completely sandboxed, and there will be no interface between them.


4, What is a dockfile?

Dockerfile A text document that contains commands for composite images, which can be invoked in the command line.


5, What is docker compose?

Can manage multiple Docker Containers form an application,Define a YAML Configuration file in format docker-compose.yml,Write the calling relationship between multiple containers.

Then, just one command can start at the same time/Close these containers.


  • What is portal?

Portal is a graphical management tool of Docker


7, What is the version of docker used in the company?



8, Relationship between image and container?

The container is writable and the image is readable. A container is an instance of a mirror, and a mirror is a static backup of a container.


9, What is the principle of redis based setnx in distributed locks and the difference between set and setnx?

The distributed lock is based on the SETNX principle. If SETNX returns 1, it indicates that the process has obtained the lock.
If SETNX returns 0, it indicates that other processes have obtained locks and cannot enter the critical area. The process can continuously try SETNX operations in a loop to obtain locks.

In redis, SET associates the string value value with the key. If the key already holds other values, SET overwrites the old value and ignores the type.

SETNX is the value value that can be set if and only if the key does not exist. If the given key already exists, SETNX will not take any action.


10, What is spring cloud? What are the components in spring cloud? Describe its principle respectively?

The core of spring cloud architecture is Eureka registry, which is an address book. All the p-side and c-side will be registered above. The c-side in cloud calls the feign component of the p-side application. When an application causes a problem with a network request, the hystrix component implements a fault-tolerant mechanism. When the number of user requests becomes larger, the ribbon component is used to realize the load balancing of the client. The server-side load balancing usually uses nginx reverse proxy. There are components similar to servlet filter in spring cloud, and zuul gateway component performs security filtering on the whole service architecture. When using a service to call multiple feign components, sleuth+zipkin components are used for service tracing and can be used to debug interfaces (tracing problems). config component for unified configuration.

dubbo is based on RPC and spring cloud is based on RESTful.

Components ribbon, feign, hstrix, eureka, zuul.



11, What is jmeter?

Apache JMeter yes Apache Organization based development Java Stress testing tools. For stress testing software, it was originally designed for Web Application testing, but later extended to other testing areas.

Send a request to the server to obtain the statistical information of the target service and generate reports in different formats.


The third round of interview questions

1. Describe the functional modules of your last company's SSM project?

2. Describe the functional modules of your last company's dubbo+zookeeper project?

3. Describe the functional modules of your last company's spring cloud project?

4. Describe the idea of permission module in your last company's project?

5. Describe the idea of the report module in the previous company's project?


The fourth round of interview questions

1, What is mybatis?

A persistence layer framework, which is similar to the operation of JDBC accessing database,
We say that the objects used by JDBC include Connection object, PreparedStatement object and ResultSet object.
The core objects of Mybatis framework include SqlSessionFactoryBuilder object, SqlSessionFactory object and SqlSession object.
And the biggest difference between myibatis framework and hibernate framework is that mybatis has high flexibility.


2, What is spring?

Before spring came out, the service layer used new to call dao layer.
After spring comes out, the service layer and dao layer will be managed in the spring container. This is the first feature of spring, which we call IOC, control inversion.
spring also has a feature, which we call AOP. In the vernacular, "facing all aspects", it means that special people do special things. Many projects are public or private
The modules to be repeatedly called can be extracted by using the characteristics of AOP, such as log module.


3, What is spring MVC?

When the user sends a request to springmvc In the front-end controller in, it returns through the mapper and adapter ModelAndView Object to client. This is it. SpringMVC The basic principle of.


  • What is SSM?

There are many versions of SSM. For example, one version can be built like this, and the two core configuration files are web xml,applicationContext. xml.

1. Front end controller DispatcherServlet

2. Filter characterencoding filter


1. Scan package < context: component scan base package = "CN" / >

2.mvc driver < MVC: annotation driven / >

3. Transaction driven < TX: annotation driven transaction manager = "txmanager" / >

4. Configure data source


6. Configuration transactions

7. Data mapper

8. View parser

5, What is a collection?

A Collection has two parent interfaces, one Collection and one Map, while a Collection has two sub interfaces, one list and one Set. List has two common implementation classes ArrayList and LinkedList,
Set has two common implementation classes HashSet, TreeSet and Map, and two common implementation classes HashMap and HashTable


6, What is spring cloud?

The core of spring cloud architecture is Eureka registry, which is an address book. All the p-side and c-side will be registered above. The c-side in cloud calls the feign component of the p-side application. When an application causes a problem with a network request, the hystrix component implements a fault-tolerant mechanism. When the amount of user requests becomes larger, the ribbon component is used to realize the load balancing of the client. The server-side load balancing usually uses nginx reverse proxy. There are components similar to servlet filter in spring cloud, and zuul gateway component performs security filtering on the whole service architecture.

dubbo is based on RPC and spring cloud is based on RESTful.


7, What is Dubbo?

Dubbo and spring cloud are commonly used frameworks in distributed services. Different from cloud, Dubbo is based on RPC Protocol. It provides three core functions: interface oriented remote method invocation,

Intelligent fault tolerance and load balancing, and automatic service registration and discovery.

Dubbo is structured in a hierarchical manner to maximize loose coupling. Dubbo adopts a very simple model. Either the provider provides services or the consumer consumes services. Therefore, based on this, the two roles of service provider and service consumer can be abstracted.


8, What is message oriented middleware?

Message oriented middleware uses efficient and reliable messaging mechanism for asynchronous data transmission, and integrates distributed systems based on data communication. By providing message queue model and message passing mechanism, the communication between processes can be extended in a distributed environment.


9, What's the difference between eureka and zookeeper?

First of all, they are the functions of service registration and discovery. cloud generally selects eureka as the registration center, and dubbo generally selects zookeeper as the registration center. Based on the CAP principle, eurek is the AP principle, that is, usability and partition fault tolerance, and zookeeper is the CP principle, that is, strong consistency and partition fault tolerance.


10, The concept of distributed locks?

In the distributed system, due to the distribution of the distributed system, that is, multithreading and multiprocessing, and distributed in different machines, these two locks will lose the effect of the original lock. We need to implement the distributed lock - distributed lock ourselves.
In a multithreaded environment, multiple threads access the same resource at the same time, resulting in thread insecurity. Distributed locks are used to solve this thread safety problem.

Distributed lock and lock are used in distributed rush purchase; The second user must wait for the first user to complete the rush purchase; Using setnx settings to solve security problems, the disadvantage is that the performance is too low.



The fifth round of interview

1.Dead letter, delay, retry queue

Dead letter, delay, retry queue

# Dead letter queue

DLQ(Deal Letter Queue), dead letter queue. When a message becomes a dead letter in the queue, it can be re sent to DLQ. Binding to the queue with DLQ is the dead letter queue.

# When do I need a dead letter queue

·Message rejected

·Message expiration

·The queue has reached its maximum length


The producer produces a message and stores it in the ordinary queue; Set the expiration time of the queue to {10 seconds. If there is no consumer consumption message within 10 seconds, it is determined that the message is expired; At this time, if the dead letter queue is set, the expired message is lost to the dead letter queue switch and then stored in the dead letter queue.

# Delay queue

As the name suggests, it means delaying the execution of messages. For example, we can add a queue and set its timeout to {10 seconds without setting any consumers. When the message times out, we can put the message into the dead letter queue and let consumers listen to the dead letter queue to achieve the effect of delaying the queue.

# Retry Queue

The retry message is delivered to the consumer again after a certain time point of delay (the service can be set). If repeated consumption continues to fail for a certain number of times, it will be delivered to the dead letter queue. Finally, manual intervention is required.


  1. Parents Delegation Model

Parents Delegation Model

# Class loader

# Open class loading

ClassLoader is an innovation of Java language and an important reason for the popularity of Java. In the "loading" process of the first stage of class loading, the binary byte stream defining this class needs to be obtained through the fully qualified name of a class. The code block to complete this action is the class loader. This action is implemented outside the Java virtual machine, so that the application can decide how to get the required classes.

The virtual machine specification does not specify that the binary byte stream should be obtained from a Class file, or where and how to obtain it at all. This openness makes Java fully used in many fields.

# Class loader and class uniqueness

Although the Class loader is only used to implement the loading action of classes, for any Class, the Class loader that loads it and the Class itself need to jointly establish its uniqueness in the Java virtual machine. Generally speaking, whether the two classes in the JVM are "equal" must first be loaded by the same Class loader. Otherwise, even if the two classes come from the same Class file and are loaded by the same virtual machine, as long as the Class loaders are different, the two classes must be unequal.

The "equality" here includes the return results of the Class object's , equals() method, isAssignableFrom() method and isInstance() method, as well as the determination of the object's ownership relationship using the , instanceof , keyword.



# Parents Delegation Model

Class loader type

From the perspective of # Java virtual machine, there are only two different class loaders: one is Bootstrap ClassLoader, which is implemented in # C + + language (in HotSpot virtual machine) and is a part of the virtual machine itself; The other is all other class loaders. These class loaders are implemented in Java language, independent of the virtual machine, and all inherit from Java lang.ClassLoader.

From the perspective of developers, class loaders can be subdivided into:

  • Bootstrap class loader: responsible for loading Java_ Load the class library under home / lib into memory (such as rt.jar). Since the boot class loader involves the local implementation details of the virtual machine, the developer cannot directly obtain the reference of the boot class loader, so it is not allowed to operate directly through the reference.
  • Standard Extension class loader: implemented by Sun's ExtClassLoader (sun.misc.Launcher$ExtClassLoader). It is responsible for putting Java_Home /lib/ext or by the system variable Java The class library in the location specified by ext.dir is loaded into memory. Developers can use the standard Extension class loader directly.
  • Application class loader: it is implemented by Sun's AppClassLoader (sun.misc.Launcher$AppClassLoader). It is responsible for loading the class library specified in the System CLASSPATH into memory. Developers can use the System class loader directly. Since this class loader is the return value of the getSystemClassLoader() method in ClassLoader, it is generally called System loader.

In addition, there are custom class loaders, and the hierarchical relationship between them is called the {parent delegation model of class loader. The model requires that except for the top-level startup class loader, other class loaders should have their own parent class loader, and this parent-child relationship is generally realized through Composition rather than Inheritance.


Parents Delegation Model

# Parental delegation model process

When a specific class loader receives a request to load a class, it first delegates the loading task to the parent class loader and recurses in turn. If the parent class loader can complete the class loading task, it returns successfully; Only when the parent class loader cannot complete this loading task can it load it by itself.

The advantage of using the two parent delegation model is that Java classes have a hierarchical relationship with priority along with their class loaders. For example, the class java Lang.Object, which exists in rt.jar. No matter which class loader wants to load this class, it is ultimately delegated to the Bootstrap ClassLoader at the top of the model for loading. Therefore, the object class is the same class in various class loader environments of the program. On the contrary, if there is no parental delegation model, but each class loader loads it by itself, if the user writes a Java Lang. object , and put it in ClassPath, there will be many different object classes in the system, and the program will be confused. Therefore, if a developer tries to write a Java class with the same name as that in the {rt.jar} class library, it can be compiled normally, but it can never be loaded and run.

# System implementation of parental delegation model

In Java In the # loadClass() method of lang. classloader # first check whether it has been loaded. If it has not been loaded, call the # loadClass() method of the parent class loader. If the parent loader is empty, the startup class loader is used as the parent loader by default. If the parent fails to load, throw a "ClassNotFoundException" exception, and then call your own "findClass() method to load.

Note that the parental delegation model is the implementation of the class loader recommended by Java designers to developers, and is not mandatory. Most class loaders follow this model, but there are also cases of large-scale destruction of the parental model in JDK, such as the exit of Thread Context ClassLoader


  1. zookeeper fake brain fissure

Zookeeper fake brain crack

This problem is the multi master and multi slave problem caused by the network shock of the service cluster. The solution is to set the timeout of service switching, but it will also lead to the failure to meet the requirements of high availability.


  1. MySQL optimization

MySQL optimization

  • When querying table Association, you must follow the principle of "small table driving large table";
  • When using the "where" condition of the query statement, the "where" function is not allowed, otherwise the index will become invalid;
  • When using a single table query, try not to use {OR} for the same field, because it may lead to index invalidation. You can use {UNION} instead;
  • The LIKE # statement is not allowed to start with%, otherwise the index will become invalid;
  • The combined index must follow the "from left to right" principle, otherwise the index will fail;
  • The number of indexes should not be too many. It should be determined according to the actual situation and should not exceed {10 as far as possible;
  • Each table must have a {primary key to speed up query efficiency;
  • Sub table: the table name can be made according to the one digit, ten digit or hundred digit (and so on) in the mantissa of the business field to achieve the purpose of sub table;
  • Sub database: the name of the database can be made according to the one digit, ten digit or hundred digit (and so on) in the mantissa of the business field to achieve the purpose of sub database;
  • Table partition is similar to hard disk partition. It can put the data of a certain period of time in the partition to speed up the query speed. It can be used in combination with "table partition + table partition";

# Artifact EXPLAIN statement

EXPLAIN shows how MySQL uses indexes to process SELECT statements and join tables. It can help SELECT better indexes and write more optimized query statements.

The use method is to add "EXPLAIN" before the "SELECT" statement, such as:

EXPLAIN SELECT * FROM tb_item WHERE cid IN (SELECT id FROM tb_item_cat)


    • id: SELECT id. This is the query serial number of SELECT
    • select_type: SELECT type, which can be any of the following
    • Table: the table referenced by the output row
    • Table partitions: partitions
    • Type: join type. Various connection types are given below, which are sorted according to , from the best type to the worst type ,

System: the table has only one row (= system table). This is a special case of const join type.


Indicate which index MySQL can use to find rows in the table

    • Key: displays the key (index) that MySQL actually decides to use. If no index is selected, the key is NULL.
    • key_len: displays the key length determined by MySQL. If the key is NULL, the length is NULL.
    • ref: displays which column or constant is used to select rows from the table together with key.
    • Rows: displays the number of rows MySQL thinks it must check when executing a query. Data multiplication between multiple rows can estimate the number of rows to process.
    • Filtered: displays the percentage estimate of the number of rows filtered by the condition.
    • Extra: this column contains the details of MySQL solving the query


  1. New features of JDK8

New features of JDK8


Two important features are listed below:

  • Lambda expression (anonymous function)
  • Stream multithreaded parallel data processing (important)
  • The default method of the interface only needs to use the keyword "default". This feature is also called "extension method"
  • Lambda expression
  • Functional interface refers to an interface that contains only one abstract method. Every Lambda expression of this type will be matched to this abstract method. You just need to add @ FunctionalInterface @ annotation to your interface
  • Use the:: Double colon keyword to pass methods (static and non static)
  • Predicate interface and Lambda expression
  • Function interface
  • The Supplier interface returns a value of any type. Unlike the Function interface, this interface {does not have any parameters
  • The Consumer interface receives a value of any type. Unlike the Function interface, this interface {does not have any value
  • Optional class

New features

Little chestnut

package com.funtl.jdk8.feature.lambda;

import java.util.Arrays;import java.util.List;import;


* basic usage of Lambda

 * <p>Title: BaseLambda</p>

 * <p>Description: </p>


 * @author Lusifer

 * @version 1.0.0

 * @date 2019/1/6 10:42

 */public class BaseLambda {

    public static void main(String[] args) {






* Lambda traversal


    public static void testForeach() {

/ / define an array

        String[] array = {

"Neal era machinery",

"About my reincarnation as shrem",

"Strength first teacher",

"Hell girl"



/ / convert to collection

        List<String> acgs = Arrays.asList(array);


/ / traditional traversal method

        System.out.println("traditional traversal method:");

        for (String acg : acgs) {





/ / use Lambda expressions and functional operations

        System.out.println("Lambda expression and function operation:");

        acgs.forEach((acg) -> System.out.println(acg));



/ / use the double colon operator in Java 8

        System.out.println("use double colon operator:");






* Stream de duplication

* String and Integer can be de duplicated using this method


    public static void testStreamDuplicates() {

        System.out.println("Stream de duplication:");


/ / define an array

        String[] array = {

"Neal era machinery",

"Neal era machinery",

"About my reincarnation as shrem",

"About my reincarnation as shrem",

"Strength first teacher",

"Strength first teacher",

"Hell girl",

"Hell girl"



/ / convert to collection

        List<String> acgs = Arrays.asList(array);


/ / Stream de duplication

        acgs =;


/ / print




  1. JavaScript this keyword

JavaScript this keyword



Any environment that executes # JavaScript # is called # execution context. By default, the execution context is global, which means that if the code is executed as part of a simple function call, the # this # variable will reference the # global object. In the case of a browser, the global object is a windows object. However, in the # NodeJS # environment, this # value is a special # global # object.

Simple function

/ / case 1: simple function, this - > window in browser, this - > global in NodeJS

  function simple1() {

    console.log("case 1, simple function");

    console.log("I'm a simple function, this points to window");




Strict mode

/ / case 2, strict mode, this - > undefined

  function simple2() {

    'use strict';

    console.log("case 2, strict mode");

    console.log("I am in strict mode, and this points to undefined");




# Constructor

When we call "new User", JavaScript will create a new object in the User function and save it as "this". Then, the name, age , and , info , attributes are added to the newly created , this , object.

/ / case 3: constructor. At this time, this object is created in the execution context, and three attributes of name, age and info are added to this object

  function User(name, age) { = name;

    this.age = age; = function () {

      console.log("I am the info attribute in the User object")

      console.log(`${} ${this.age}`);


    console.log("case 3, constructor");

    console.log("I am a User object. I created this object in the execution context and added three attributes: name, age and info");



  let andy = new User('Andy', 22);;

Simple object 1

When this function is called, it points to a common object

/ / case 4: simple object

  let user = {

name: 'Xiao Ming',

    age: userAgeFunction,

    sex: function () {

      console.log("I am the sex attribute of the user object, and this points to the user object, not the global object");



    talk: function () {




  function userAgeFunction() {

    console.log("I am the age attribute of the user object, and this points to the user object, not the global object");



  console.log("case 4, simple object");



  let talk =;

  console.log("I'm talk. I call the talk attribute of the user object as an ordinary function, so this here points to window");


Simple object 2

Inside the age , function, this , points to the , lee , object, but inside the , innerAge , function, this , points to the global object. The rule tells us that whenever an ordinary function is called, then , this , will point to the global object.

/ / case 5, simple object 2

  let lee = {

    name: 'lee',

    birth: 1998,

    age: function () {

      console.log("I am the age attribute of the lee object, and this points to the lee object, not the global object");


      function innerAge() {

        console.log("although I am the innerAge() function in the age attribute of the lee object, I will be called normally, so this here points to the window instead of the lee object");



/ / the innerAge() ordinary call inside the age attribute of lee object is initiated here, so this in this function points to window




  console.log("case 5, simple object");



  • call: point this to the target object
  • apply: point # this # to the target object and use this method when the parameter form is array
  • bind: point this to the first parameter passed and return a new method

    function User(username, password) {

        this.username = username;

        this.password = password;

        this.displayUser = function() {

            console.log(`User: ${this.username} ${this.password}`);




    let user1 = new User("admin", "123456");

    let user2 = new User("guest", "abcdef");


    console.log("case 6, call apply bind");

    console.log("I am the user1 object");


    console.log("I am user2 object")


    console.log("I am a user1 object, and I used the call method to point my this to user2");

    console.log("I am a user1 object, and I used the apply method to point my this to user2")


    console.log("I am a user1 object, I used the bind method to point my this to user2 and returned a new method")

    let user2Display = user1.displayUser.bind(user2)



  1. token and session

token and session

What is a token?

Token is a string of strings generated by the server, which is used as a token for the client to request. After the first login, the server generates a token (a string of strings) and returns the token to the client. After receiving the request, the page only needs to find the token to obtain the information without entering the login name and password.

Token is generally used to verify the data indicating identity or other password data; A token can be passed by url, submitted by post, or sandwiched in the header of http.

What is session?

A session is literally a session.

In order to let the server know where the current request comes from, the server assigns a different "identity" (similar id) to each client, and then the client carries this identity (id) every time it sends a request. In this way, the server can know who sent the request.

The difference between session and token:

The server uses session to temporarily save the user information on the server. After the user leaves the website, the session will be destroyed.

However, session has one defect: if the web server performs load balancing, the session will be lost when the next operation request reaches another server.

The biggest feature of token is that it supports cross platform operation. Tokens can be retained whether on App or PC.


8. Microservices

1.API management


RequestMappingHandlerMapping is an important role in spring MVC. It determines which Controller each URL is distributed to.

We can customize the loading process of mvspringadapteradaptingthrough the following procedure.



  1. Service fuse

Fuse of Hystrix

Netflix' Hystrix It is the first service middleware dedicated to fuse. When it was released to the public in 2012 to provide a microservice architecture with "greater tolerance for delay and failure", Netflix has been widely used internally for more than a year. According to this project According to the description of, Hystrix has always been one of the basic components of Netflix service middleware until it entered the maintenance mode at the end of 2018, which marks that "[Focus] has shifted to the implementation that is more suitable for the real-time performance of applications rather than pre configured settings."

Hystrix is a Java library that developers can use to encapsulate service calls with fuse logic. Based on the threshold value, it can immediately determine the call failure and execute the rollback logic. For details, refer to Part I . In addition to providing timeout and concurrency limits, it can also publish metrics to the monitoring tool. Finally, when with Archaius When used with libraries, it can also support dynamic configuration changes.

Fusing in service grid


Istio Is a service grid, which supports fusing based on connection pool, request of each connection and fault detection parameters. It does this with the help of so-called "destination rules", which tell each Envoy agent what strategy to apply to communication and how to apply it. This step occurs after routing, but this is not always ideal. The target rule can specify the limit of load balancing, the size of the connection pool, and the parameters that finally meet the "outlier" condition, so that unhealthy instances can be deleted from the load balancing pool. This type of fuse is good at protecting the client from server failure, but because the target rule is always applied in the cluster, it lacks a method to limit the circuit breaker to a subset of the client. In order to realize the combination of circuit breaker and quality of service mode, routing rules of multiple client subsets must be created, and each subset has its own target rules.

3.Micro service tracking


Implementation of service tracking system


The above is the architecture diagram of the service tracking system. You can see that a service tracking system can be divided into three layers.

The data acquisition layer is responsible for data embedding and reporting.

The data processing layer is responsible for data storage and calculation.

The data display layer is responsible for the graphical display of data

The role of service tracking
First, optimize the system bottleneck.
By recording the time spent on each link, we can quickly locate the bottleneck of the whole system. For example, when you visit the microblog home page, you find that it is very slow. It must be caused by some reason. It may be the operator's network delay, the gateway system exception, a service exception, the cache or database exception. Through service tracking, we can observe from a global perspective, find out the bottleneck of the whole system, and then make targeted optimization.

Second, optimize link calls.
Through service tracing, you can analyze the path of the call, and then evaluate whether it is reasonable. For example, the downstream of a service call depends on multiple services. Through the call chain analysis, we can evaluate whether each dependency is necessary and whether the service dependency can be reduced through business optimization.

In addition, general businesses will deploy services in multiple data centers to achieve remote disaster recovery. At this time, there is often A situation that service A calls service B in another data center instead of service B in the same data center. The apparent distance of calls across data centers will have A certain network delay. For example, the network delay of thousands of kilometers in Beijing and Guangzhou may reach more than 30ms, which is almost unacceptable for some services. By analyzing the call link, we can find out the service call across the data center, so as to optimize and avoid this situation as much as possible.

Third, generate network topology.
Through the link information recorded in the service tracking system, a network call topology diagram of the system can be generated. It can reflect which services the system depends on and what the call relationship between services is at a glance. In addition, the detailed information of service call can also be marked on the network topology, which can also play the role of service monitoring.

Fourth, transparent transmission of data.
In addition to service tracking, there is often a demand in business that some user data can be passed down from the beginning of the call, so that each service in the system can obtain this information. For example, when a business wants to do some A/B tests, it wants to pass the switching logic of A/B tests down through the service tracking system. After each layer of services can obtain the switching value, it can conduct A/B tests uniformly.


Principle of service tracking system
Its core idea is the call chain: connect the same request distributed on each service node through a globally unique ID, so as to restore the original call relationship, track system problems, analyze call data and count various system indicators.

It can be said that various service tracking systems are derived from Dapper. The more famous ones are Zipkin of Twitter, eagle eye of Alibaba, MTrace of meituan, etc. (the originator of service tracking system: a paper published by Google, Dapper, a large-scale distributed systems tracking infrastructure, explains in detail the implementation principle of service tracking system.)

To understand the principle of service tracking, we must first understand some basic concepts: traceId, spanId, announcement, etc. Dapper's paper is quite clear, but it may be a little difficult for beginners to understand. The introduction of the principle of meituan's MTrace is relatively easy to understand. Next, I'll take MTrace as an example to tell you the implementation principle of the service tracking system in detail. Although the principle is somewhat obscure, it is something you must master. Only by understanding the basic concept of service tracking can you better implement it.

4.Configuration center local

Configuration takes effect in real time:

In the traditional static configuration mode, if you want to modify a configuration, you can only republish the application after modification. To achieve dynamic performance, you can choose to use the database and visit the database through regular polling to sense the change of configuration. When the polling frequency is low, the delay of sensing configuration change is long, and when the polling frequency is high, the delay of sensing configuration change is short. However, compared with the loss performance, it is necessary to make a compromise between real-time performance and performance. The configuration center manages dynamic configuration specifically for this business scenario, taking into account real-time and consistency.

Configuration management process:

A series of configuration management related features such as configuration permission control, gray publishing, version management, format verification and security configuration are also part of the configuration center.

Introduction to open source configuration center

At present, there are many configuration centers in the market: (sorted by open source time)


In July 2014, Baidu's open source configuration management center also has the ability to manage configuration, but it is no longer maintained. The most recent submission was two years ago.

Spring Cloud Config

Open source in September 2014, Spring Cloud ecological component, which can be seamlessly integrated with Spring Cloud system.


In May 2016, Ctrip's open source configuration management center has the characteristics of standardized authority and process governance.


In June 2018, Alibaba's open source configuration center can also do DNS and RPC service discovery.

Comparison of core concepts of configuration center

Since Disconf is no longer maintained, let's compare Spring Cloud Config, Apollo and Nacos.
The concepts of Spring Cloud Config, Apollo and Nacos in the field of configuration management are basically the same, but there are some differences. Some important concepts will be involved in the process of using configuration.


Application is the basic unit of the client system. Spring Cloud Config associates the application name with the file name in the corresponding Git, which can isolate multiple application configurations from each other. The configuration of Apollo is under an application (in addition to the public configuration), which also plays the role of isolating multiple application configurations from each other. The application concept of Nacos is relatively weak. There is only one additional attribute used to distinguish the configuration. However, Group can be used as the application field to isolate.


Different clusters can be built in different environments, which can play the role of physical isolation. Spring Cloud Config, Apollo and Nacos all support multiple clusters.

Label profile & Environment & namespace

Spring Cloud Config can use label and profile for logical isolation. Label refers to the branch of remote warehouse. Profile is similar to Maven Profile, which can distinguish environment, such as {application} - {profile} properties.

The namespace of Nacos, like the environment of Apollo, is a logical concept and can be used as a logical isolation of the environment. The namespace in Apollo refers to the name of the configuration, and the specific configuration item refers to a Property in the configuration file.

Comparison of configuration management functions

As a configuration center, the whole management process of configuration should have the ability of process.

Gray Publishing

Gray publishing of configuration is an important function of the configuration center. When the impact of configuration change is large, it is necessary to verify whether the configuration change meets the expectation in some application instances, and then push it to all application instances.

Spring Cloud Config supports specifying the machine to update the configuration through the destination parameter of the / bus/refresh endpoint, but the whole process is not automatic and systematic.

Apollo can directly publish the IP of the designated publishing machine on the console, and then publish it in full, which is more systematic.
Nacos is currently released to version 0.9 and does not support grayscale publishing.

Authority management

Configuration changes and code changes are changes to the application operation logic. Important configuration changes often bring nuclear bomb effects. The authority control and audit ability of configuration changes are also important functions of the configuration center.

Spring Cloud Config relies on Git's permission management ability. The open source GitHub permission control can be divided into Admin, Write and Read permissions, and the permission management is relatively perfect.

Apollo manages the configuration permissions through the project dimensions. The owner of a project can authorize other users to modify and publish the configuration permissions.

At present, Nacos does not have the ability of permission management.

Version Management & rollback

When the configuration change does not meet the expectation, it needs to be rolled back according to the release version of the configuration. Spring Cloud Config, Apollo and Nacos all have configuration version management and rollback capabilities. You can view configuration changes or rollback operations on the console. Spring Cloud Config uses Git for version management, which is more convenient.

Configure format verification

Application configuration data stored in the configuration center is generally stored in a configuration format, such as Properties, Jason, Yaml, etc. if the configuration format is wrong, the client will fail to parse the configuration and cause production failure. The configuration format verification of the configuration center can effectively prevent human error operation, which is just a requirement in the core function of the configuration center.
Spring Cloud Config uses Git. At present, it does not support format verification. The correctness of the format depends on the R & D personnel.
Apollo and Nacos will check the correctness of the configuration format, which can effectively prevent human errors.

Listening query

When troubleshooting or making statistics, you need to know which application instances use a configuration and which configurations are used by an instance.
Spring Cloud Config uses Spring Cloud Bus to push configuration changes. Spring Cloud Bus is compatible with RabbitMQ, Kafka, etc., and supports querying the subscription relationship between Topic and Consumer.
Apollo can view the instance list of listening configuration through the gray-scale instance list, but the instance listening configuration (called namespace by Apollo) has not been shown yet.

Nacos can view the instance listening configuration and the instance listening configuration.

Basically, these three products have the ability to monitor and query. In our own use process, Nacos is relatively simple to use and easier to use.

Multi environment

In actual production, the configuration center often needs to involve multiple environments or clusters. During business development, the development environment and production environment can be separated, or there are multiple production environments according to different business lines. If the interaction between various environments is relatively small (the development environment affects the stability of the production environment), the configuration center can support multiple environments through logical isolation.

Spring Cloud Config supports the isolation of multiple environments in the way of profiles. By configuring the profiles of multiple profiles on Git, the corresponding profiles can be accessed by specifying the profiles when the client starts.

Apollo also supports multiple environments. When creating a configuration on the console, you need to specify the environment where the configuration is located. When the client starts, you need to specify the JVM parameter ENV to access the configuration file of the corresponding environment.

Nacos supports multiple environments through namespaces. The configuration of each namespace is isolated from each other. The client can achieve logical isolation by specifying the namespace it wants to access.

Multi cluster

When the stability requirements are relatively high and each environment is not allowed to affect each other, multiple environments need to be physically isolated through multiple clusters.

Spring Cloud Config can realize physical isolation by building multiple sets of config servers and Git using multiple warehouses of the same Git.

Apollo can build multiple sets of clusters. Apollo's console and data update push service are deployed separately. Deploying one set of console can control multiple clusters.

The Nacos console and back-end configuration service are deployed together and can support multiple clusters through different domain name switching.

Comparison of configuring real-time push

When the configuration changes, the configuration center needs to push the configuration to the application client in real time.

Both Nacos and Apollo configuration push are based on HTTP long polling. The client establishes an HTTP long connection with the configuration center. When the configuration changes, the configuration center pushes the configuration to the client.


Spring Cloud Config native does not support configured real-time push. It needs to rely on Git's WebHook, Spring Cloud Bus and client / bus/refresh endpoint:


Based on Git WebHook, configuration change triggers server-side refresh


The Server side receives the request and sends it to the Spring Cloud Bus


Spring Cloud Bus receives the message and notifies the client


The client receives the notification and requests the Server to obtain the latest configuration




5.API gateway

1. Introduction to API gateway

API gateway is a server and the only entrance to the system. From the perspective of object-oriented design, it is similar to appearance pattern. API gateway encapsulates the internal architecture of the system and provides a customized API for each client. It may also have other responsibilities, such as authentication, monitoring, load balancing, caching, request fragmentation and management, and static response processing.

The core point of API gateway mode is that all clients and consumers access micro services through a unified gateway and handle all non business functions at the gateway layer. Generally, the gateway is also an access API that provides REST/HTTP. The server registers and manages services through API-GW.

2. Integration into architecture


API gateway is responsible for service request routing, composition and protocol conversion. All requests from the client first pass through the API gateway, which then routes the requests to the appropriate microservices. API network management often processes a request by calling multiple microservices and merging the results. It can convert between Web protocols (such as HTTP and WebSocket) and non Web friendly protocols used internally.

The API gateway can also provide a customized API for each client. Typically, it exposes a coarse-grained API to mobile clients. For example, consider the scenario of product details. API gateway can provide an endpoint (/ productdetails?productid=xxx), so that mobile clients can obtain all product details through one request. The API gateway processes the request by calling various services (product information, recommendations, comments, etc.) and merging the results.


6.Service registration discovery

Client service discovery mode

When using client service discovery, the client is responsible for determining the network address of available service instances and load balancing around them. The client sends a request to the service registry, which is a database of available service instances. The client uses a load balancing algorithm to select an available service instance to respond to the request. The following figure shows the architecture of this mode:

The network address of the service instance is dynamically allocated. Moreover, the configuration of service instances often changes due to automatic expansion, failure and update. In this way, your client code needs a more flexible set fine Service discovery mechanism.

There are two main service discovery modes: client side discovery and server side discovery. Let's first look at client service discovery.

Client service discovery mode

When using client service discovery, the client is responsible for determining the network address of available service instances and load balancing around them. The client sends a request to the service registry, which is a database of available service instances. The client uses a load balancing algorithm to select an available service instance to respond to the request. The following figure shows the architecture of this mode:

When a service instance is started, its network address will be written to the registry; When the service instance terminates, it is deleted from the registry. The registry of this service instance passed heartbeat Mechanism dynamic refresh.

Netflix OSS provides a good example of client service discovery. Netflix Eureka is a service registry that provides a REST API to manage the registration of service instances and query available instances. Netflix Ribbon is an IPC client that handles load balancing of available service instances with Eureka. Eureka will be discussed in depth below.

The client-side service mode also has advantages and disadvantages. This mode is relatively direct, but there is no other dynamic part except the service registry. Moreover, because the client knows the available service instances, it can make intelligent and apply clear load balancing decisions, such as always using hash algorithm. A major defect of this model is that the client and service registry are one-to-one corresponding. The client service discovery logic must be implemented for each programming language and framework used by the service client.

Server side service discovery mode

The following figure shows the architecture of this model
Client through load balancing weighing apparatus When sending a request to a service, the load balancer will query the service registry and route the request to the available service instances. Through the service discovery of the client, the service instance is registered and registered on the service registry cancellation.

AWS ELB (elastic load blaster) is a server-side service discovery router. An ELB is usually used to balance external traffic from the Internet, or ELB can be used to balance flow to VPC (Virtual Private Cloud) traffic. When a client sends a request (HTTP or TCP) through ELB, DNS is used. ELB will balance the traffic of these registered EC2 instances or ECS (EC2 Container Service) containers. Without another service registry, EC2 instances and ECS containers will only be registered on the ELB.

HTTP servers and load balancers like Nginx and Nginx Plus can also be used as server-side service discovery load balancers. For example, consult template can be used to dynamically configure the reverse proxy of Nginx.

The Consul Template periodically generates arbitrary configuration files from the data stored in the Consul service registry. Whenever the file changes, a shell command is run. For example, the consult template can generate an Nginx.exe that configures a reverse proxy Conf file, and then run a command to tell Nginx to reload the configuration. There is also a more complex implementation to dynamically reconfigure Nginx Plus through HTTP API or DNS.

Some deployment environments, such as Kubernetes and Marathon, run an agent on each host in the cluster. This agent assumes the role of server-side service discovery load balancer. In order to send a request to a service, a client routes the request through a proxy using the IP address of the host and the port assigned by the service. The agent will send the request directly to the service instances available on the cluster.

The server-side service discovery model also has advantages and disadvantages coexist . The biggest advantage is that the details of service discovery are abstracted from the client. The client only needs to send a request to the load balancer without realizing the service discovery logic for each language and framework used by the service client; In addition, this model also has some problems, unless the load balancer is provided by the deployment environment and is another available system component that needs to be started and managed.

Service Registry

Service registry is the key part of service discovery. It is a database containing the network address of service instances. It must be highly available and up-to-date. The client can cache the network address obtained from the service registry. However, this information will eventually become invalid and the client will not find the service instance. Therefore, the service registry is composed of a server cluster, which is consistent through the application protocol.

As mentioned above, Netflix Eureka is a good example of a service registry. It provides a REST API to register and query service instances. A service instance registers its network location through POST request, and re registers through a PUT request every 30 seconds. An entry in the registry will be deleted because of an HTTP DELETE request or instance registration timeout. The client retrieves the registered service instance through an HTTP GET request.

Netflix achieves high availability by running one or more Eureka servers in the availability zone of each EC2. Each Eureka server running on an EC2 instance has an elastic IP address. DNS TEXT records is used to store Eureka cluster configuration. In fact, it is a mapping from the available zone to the list of Eureka server network addresses. When an Eureka server starts, it will send a request to DNS to retrieve the configuration of Eureka cluster, locate nodes, and assign itself an unoccupied elastic IP address.

Eureka client (service and service client) queries DNS to find the network address of Eureka server. Clients prefer to use this available In the area If there is no Eureka server available, the client will use another Eureka server in the availability zone.

Examples of other service registrations include:

  • Etcd: a highly available, distributed and consistent key value storage for shared configuration and service discovery. Both Kubernetes and Cloudfoundry use etcd;
  • Consult: a tool for discovering and configuring services. Clients can use its API to register and discover services. Consul can perform high availability monitoring;
  • Apache Zookeeper: a commonly used high availability coordination service designed for distributed applications. At first, Zookeeper was a sub project of Hadoop, and now it is a top-level project.

Some systems, such as Kubernetes, Marathon and AWS, do not have a clear service registration component, which is built into the basic settings.

Let's take a look at how the service instance is registered in the registry.

Service Registration

As mentioned earlier, service instances must be registered and unregistered from the registry. There are many ways to handle the registration and unregistering process. One option is to register the service instance itself, that is, the self registration mode. Another option is the registration of other system component management service instances, that is, the third party registration mode.

The self registration pattern

In the self registration mode, the service instance is responsible for registering and unregistering from the service registry. If necessary, a service instance sends a heartbeat request to prevent the registration from expiring. The following figure shows the architecture of this model:

Netflix OSS Eureka client is a good example of this approach. Eureka client handles all problems of service instance registration and logout. Spring Cloud implements a variety of modes including service discovery, which simplifies the automatic registration of Eureka's service instances. Java configuration classes can be annotated only through the @ EnableEurekaClient annotation

The same is true for the self registration mode Pros and cons coexist. One of the advantages is that it is simple and does not require other components. The disadvantage is that the service instance corresponds to the service registry, and the registration code must be implemented for each programming language and framework used in the service.

The third party registration pattern

In the third party registration mode, the service instance will not register itself in the service registry, and another system component, service registrar, is responsible for it. Service registrar tracks the changes of running instances by polling the deployment environment or subscribing to events. When it notices a new available service instance, it will register in the registry. Service registrar will also unregister the stopped service instance. The following figure shows the architecture of this mode.  
The registry service project is an example of the open source registry service project. It will automatically register and unregister services deployed like the Docker container. The Registrar supports service registration such as etcd and consult.

Another example of service registrar is NetflixOSS Prana. It is mainly used for services written in non JVM language. It is a "two round" application matched with service instances. Prana will register and unregister the instance on Netflix Eureka.

Service register is a built-in component of the deployment environment. EC2 instances created by Autoscaling Group can be automatically registered by ELB. Kubernetes service can also register automatically.

The main advantage of the third party registration mode is that it decouples the service and service registry. There is no need to implement service registration logic for every language and framework. Service instance registration is implemented by a dedicated service. The disadvantage is that in addition to being built into the deployment environment, it is also a highly available system component, which needs to be started and managed.


7.How to design the idempotency of distributed service interface

Interviewer psychological analysis

From this question, the interviewer has entered the actual production interview.

How to ensure idempotency of an interface in a distributed system? This is actually a technical problem of production environment that you must consider when you do distributed system. What do you mean?

You see, if you have a service that provides some interfaces for external calls, the service is deployed on five machines, and then there is an interface, which is the payment interface. Then, when other users operate on the front end, they don't know why. In short, an order accidentally initiates two payment requests, and then the two requests are scattered on different machines deployed by the service. Well, as a result, the payment of an order is deducted twice.

The payment system calls the payment system twice and tries again, because the payment system calls the payment system twice, and the result is that the payment system fails to balance the order, and then we see that the payment system calls the payment system twice and tries again...

So you must know about it, otherwise the distributed system you make may be easy to bury a hole.

Analysis of interview questions

This is not a technical problem. There is no general method. This should be combined with business to ensure idempotency.

The so-called idempotency means that an interface initiates the same request multiple times. Your interface must ensure that the result is accurate. For example, you can't deduct more money, insert more data, and add 1 more to the statistical value. This is idempotency.

In fact, there are three main points to ensure idempotency:

  • For each request, there must be a unique identifier. For example, an order payment request must contain an order id. an order id can be paid once at most, right.
  • After each request is processed, there must be a record to identify that the request has been processed. A common solution is to record a status in mysql. For example, record a payment flow of this order before payment.
  • Every time you receive a request, you need to judge whether it has been processed before. For example, if an order has been paid, there is already a payment flow. If the request is sent repeatedly, the payment flow will be inserted first. The orderId already exists, the unique key constraint takes effect, and the error message will not be inserted. Then you don't have to deduct any more.

In the actual operation process, you should combine your own business, such as using redis and orderId as the unique key. Only when this payment flow is successfully inserted can the actual payment deduction be executed.

The requirement is to pay an order, and a payment flow must be inserted_ ID creates a unique key. Before you pay an order, insert a payment flow first_ I already went in. You can write a logo into redis and set order_id paid, the next repeat request is coming. Check the order of redis first_ If the value corresponding to the ID is "paid", it means that it has been paid. Don't pay again.


8.Use of Nginx

Nginx should be one of the most popular web and reverse proxy servers today. It is a high-performance web server born in Russia. Especially in the case of high concurrency, it has excellent performance compared with Apache.

In addition to load balancing, what other uses does it have? Let's take a look.


1, Static proxy

Nginx is good at handling static files and is a very good image and file server. Putting all static resources on nginx can make the application dynamic and static separation and better performance.

2, Load balancing

Through reverse proxy, Nginx can realize service load balancing, avoid single node failure of the server, and forward requests to different servers according to certain policies to achieve the effect of load.




Common load balancing strategies include:

1. Polling

The requests are distributed to the back-end servers in turn. It treats each server in the back-end evenly, regardless of the actual number of connections and the current system load.

2. Weighted polling

Different back-end servers may have different machine configurations and the load of the current system, so their stress resistance is also different.

Assign higher weights to machines with high configuration and low load to handle more requests; The machines with low configuration and high load are assigned a lower weight and reduce their system load. Weighted polling can deal with this problem well and distribute the requests to the back end in order and according to the weight.

3,ip_hash (source address hashing method)

According to the IP address of the client, a value is calculated through the hash function, and the size of the server list is modulo calculated with this value. The result is the serial number of the server to be accessed by the client.

The source address hash method is used for load balancing. When the list of back-end servers remains unchanged, the client with the same IP address will be mapped to the same back-end server for access every time.

4. Random

Through the random algorithm of the system, one of the servers is randomly selected for access according to the list size value of the back-end server.

5,least_conn (minimum connection number method)

Due to the different configurations of the back-end servers, the processing of requests is fast or slow. The minimum connection method dynamically selects the server with the least current backlog of connections to process the current requests according to the current connection of the back-end servers, so as to improve the utilization efficiency of the back-end services as much as possible and reasonably divert the responsibility to each server.

3, Current limiting

The current limiting module of Nginx is implemented based on the leaky bucket algorithm, which is very practical in high concurrency scenarios, as shown in the following figure:




1. Configuration parameters

1)limit_ req_ The zone is defined in the http block, $binary_remote_addr represents the binary form of saving the client IP address.

2) Zone defines the shared memory area of IP status and URL access frequency.

zone=keyword identifies the name of the zone and the size of the zone followed by a colon. The status information of 16000 IP addresses is about 1MB, so the region in the example can store 160000 IP addresses.

3) Rate defines the maximum request rate. In the example, the rate cannot exceed 100 requests per second.

2. Set current limit

burst queue size, nodelay does not limit the time between individual requests.

4, Cache

1. Browser cache and static resource cache use expire.





2. Proxy cache





5, Black and white list

1. Unlimited whitelist





2. Blacklist




9.What usage scenarios does zookeeper have?

Generally speaking, the usage scenarios of zookeeper are as follows. I'll give you a few simple ones. Just say a few:

  • Distributed coordination
  • Distributed lock
  • Metadata / configuration information management
  • HA high availability


Distributed coordination

  This is actually zookeeper It's a classic usage. In short, it's like you A The system sends a request to mq,then B System messages are processed after consumption. that A system

How to know B System processing results? use zookeeper The coordination between distributed systems can be realized. A After the system sends a request, you can zookeeper On a node

Register a listener once B The system will modify it after processing zookeeper The value of that node, A The system can receive the notice immediately and solve it perfectly.





Distributed lock

  Take a chestnut. Two modification operations are sent continuously for a certain data, and two machines receive the request at the same time, but only one machine can execute the other machine first. So now

have access to zookeeper A distributed lock is obtained by a machine after receiving the request zookeeper A distributed lock on the can create one znode,Then execute

Operation; Then another machine tries to create that znode,As a result, I found that I couldn't create it myself, because it was created by others. I had to wait until the first machine finished executing it.





Metadata / configuration information management

  zookeeper It can be used to manage the configuration information of many systems, such as kafka,storm And so on, many distributed systems will choose zookeeper To do some metadata

Management of configuration information, including dubbo Registry does not support zookeeper Are you?





HA high availability

  This should be very common, for example hadoop,hdfs,yarn And many other big data systems choose to be based on zookeeper To develop HA High availability mechanism is one

Important processes usually have two active and standby processes. When the main process hangs, it passes immediately zookeeper Switch to standby process is sensed.




First, you need to understand why the system uses distributed.

With the development of the Internet, many performance bottlenecks of traditional single project projects are becoming more and more prominent. There are several aspects of performance bottlenecks:

1. Application service layer: as the number of users increases, the number of concurrent requests increases. It is difficult for a single project to withstand the performance bottleneck caused by such a large number of concurrent requests.

2. Underlying database layer: with the development of business, the pressure of database is increasing, resulting in performance bottlenecks.

#Scenario 1: Session sharing of application system cluster

The simplest application cluster is the server cluster, such as Tomcat cluster. When applying system clusters, the most prominent problem is Session sharing. First, we can solve Session sharing through server plug-ins. The other can also be implemented through Redis and other middleware.

#Scenario 2: Service splitting of application system

Service-oriented splitting is a very popular way at present. Now they are offering micro services. Through the service-oriented splitting of traditional projects, the independent decoupling of services can be achieved, and the capacity of a single service can be expanded horizontally. The classic problem of service splitting is the problem of distributed transaction. At present, there are several commonly used distributed transaction solutions: Message final consistency, TCC compensated transaction, etc.

#Scenario 3: pressure sharing of underlying database

If the performance pressure of the system appears in the database, we can solve it by reading and writing separation, database and table separation and so on.

11.spring boot and spring cloud

1. Recovery method of virtual machine data loss caused by server power failure

This question is more partial to operation and maintenance, which is not the functional scope of our development. For the development within 3 years, it is a super outline interview question. It is best to say that you have no permission to operate the server, or that the team leader is responsible and the technical manager is responsible. Forced answers will sink into the interviewer's pit

If you are interested, you can read this article:

2. Implementation principle of springboot and springcloud


My personal understanding of springboot is that he modularized the spring framework and packaged the integrated configuration of spring and the currently used technical framework, saving users from configuring and integrating themselves during development. It greatly simplifies the construction and development of spring application development process. At the same time, it better solves the version conflict of dependent packages and the instability of references during the integration of various frameworks.

Core principles:

1> Spring boot framework is implemented based on spring MVC no configuration file (pure Java) fully annotated + built-in Tomcat embedded core, and the Main function is started.

2> Springboot core quickly integrates the principle of third-party framework: Maven inheritance dependency.

Core idea: out of the box and convention is better than configuration



Although spring cloud has "cloud", it is not a cloud computing solution, but a tool set built on the basis of spring boot to quickly build a general model of distributed systems


1. Agreed due to configuration

2. Applicable to various environments. It can be developed and deployed in PC Server or various cloud environments

3. It hides the complexity of components and provides declarative and xml free configuration

4. Use out of the box and start quickly.

5. Lightweight components. Most of the components integrated by spring cloud are lightweight.

6. Rich components and complete functions. Spring cloud provides very complete support for microservice architecture. For example, configuration management, service discovery, circuit breaker, micro service

7. Neutral and rich selection

8. Flexibility. The components of spring cloud are decoupled, and developers can choose technology flexibly as needed


SpringBoot focuses on developing individual micro services quickly and easily.

SpringCloud is a microservice coordination and management framework that focuses on the overall situation. It integrates and manages individual microservices developed by SpringBoot, and provides integrated services between services, such as configuration management, service discovery, circuit breaker, routing, micro agent, event bus, global lock, selection decision, distributed session and so on.

SpringBoot can develop projects independently of SpringCloud, but SpringCloud cannot do without SpringBoot, which is a dependency.

SpringBoot focuses on the rapid and convenient development of individual micro services, and SpringCloud focuses on the overall service governance framework.

In reality, the use of spring cloud in small projects will only increase the development cost, so spring boot is generally used in the early stage of the project, which is more efficient and fast.

3. Construction process of the project

Project construction process

Project initiation

Technology selection and project framework construction

Demand analysis

Development stage

UI interface design

Code development

Back end development (start interface development after sorting out requirements)

Front end development (depending on UI interface design and back-end interface)

Test (the complete test consists of test = = > modification = = > regression test)

functional testing

performance testing

go online




4. Where is the redis project application and what data is stored

There are many usage scenarios for redis. The answer is not only where to use it, but also why

1) Login, permission control: session data cache

  1. Solve cross domain problems,
  2. Multiple server applications to achieve session data consistency

Specific steps:

When the user logs in, the user submits the request;

Verify the user name and password on the server side;

After passing, the user information is stored in Redis, and the key in the database is session_id;

The set cookie field in the response returned by the server contains the session_id, the client stores its value in the browser after receiving it;

The request of the operation after the client contains session_id, which is extracted by the server after receiving, and gets the session in Redis to complete the business operation;

When Redis is used to share and store sessions, the session must be guaranteed_ ID, which will not be easily obtained and cracked, and set a reasonable failure time. For sensitive operations, the user must be verified again.

2) Cache of home page list and other data

This kind of data has a large amount, complex query conditions and high performance consumption. Repeated requests will lead to excessive pressure on the database, reduce query efficiency and even downtime

3) Cache of personal data such as shopping cart / collection

This kind of data is characterized by 1 many operations and fast update. redis can write, remove and modify data quickly, which matches the characteristics of this kind of data very well.

Feature 2 is the data structure. The data structure of other caches is single and does not meet the structure of this kind of data well. redis has rich data structure. The key is that its hash data type meets the requirements of this kind of data structure well


For example, in the shopping cart scenario, we first need two hashes to store. The first HASH is the relationship between the user and the shopping cart, and the second HASH is the list of goods in the shopping cart.

First get the shoppingCartId through the userId, and then get the ProductIds of the user's shopping cart through the shoppingCartId. Then you can asynchronously read the product information of the user's shopping cart through ProductIds.


Generally speaking, redis is applicable to some data with low real-time requirements but more requests.


Redis features (must be understood):

  • Memory database is fast and supports data persistence. The data in memory can be saved in disk and can be loaded again for use when restarting.
  • Redis not only supports simple key value data, but also provides storage of list, set, zset, hash and other data structures.
  • Redis supports data backup, that is, data backup in master slave mode.
  • Support services

5. How to solve high concurrency requests

High Concurrency is one of the factors that must be considered in the architecture design of Internet distributed system. It usually refers to ensuring that the system can process many requests in parallel at the same time through design.

Some common indicators related to high concurrency:

Response time: the time when the system responds to the request. For example, it takes 200ms for the system to process an HTTP request. This 200ms is the response time of the system.

Throughput: the number of requests processed per unit time.

QPS: number of requests responded to per second. In the Internet field, the distinction between this index and throughput is not so obvious.

Number of concurrent users: the number of users who simultaneously carry normal system functions. For example, in an instant messaging system, the number of simultaneous online users represents the number of concurrent users of the system to a certain extent.

There are two main ways to improve the concurrency of the system in the design of Internet distributed architecture: Scale Up and Scale Out.

Vertical expansion: improve the processing capacity of a single machine. There are two ways of vertical expansion:

(1) Enhance the performance of stand-alone hardware, such as increasing the number of CPU cores, such as 32 cores, upgrading better network cards, such as 10 Gigabit, upgrading better hard disks, such as SSD, expanding hard disk capacity, such as 2T, and expanding system memory, such as 128G;

(2) Improve the performance of stand-alone architecture, such as using Cache to reduce IO times, using asynchronous to increase single service throughput, and using lockless data structure to reduce response time;

Whether it is to improve the performance of stand-alone hardware or the performance of stand-alone architecture, there is a fatal deficiency: stand-alone performance is always limited. Therefore, the ultimate solution to the high concurrency of Internet distributed architecture design is horizontal expansion.

Horizontal expansion: as long as the number of servers is increased, the system performance can be linearly expanded. Horizontal expansion has requirements for system architecture design. How to carry out horizontal expansion design at each layer of the architecture, as well as the common horizontal expansion practices at each layer of the architecture of Internet companies

Our company started with a server with 2-core 8Gb. When user interaction began, it was immediately upgraded to 4-core 16Gb, and then upgraded to 4-core 32GB again. When the number of users comes up, start using the cluster.

Here is to expand vertically first and then horizontally

In the early stage of the project, vertical expansion is generally selected for rapid iterative development, recommended business and cost. When the project is up and the number of users is profitable, horizontal expansion will be selected to support increasingly complex needs

6. Which business in the project uses multithreading?

1. The sending of regular short messages and messages in the station involves tens of thousands of users. If a single thread is used, it will take a long time, and multithreading can greatly shorten the sending time

2. Regular operation list record (the operation between records must be independent)

3. Import mass data

7. The project has been launched. How to solve the bug and what to do if it goes down

Online bug s are generally divided into emergency and non emergency:

For urgent bug s, we will immediately organize testing and development for troubleshooting. If the code problem is repaired in real time, if there is no problem in the test after repair, we will notify the online, and then test and follow up after the online

Non urgent bugs will be submitted to bug management tools (such as Zen) for troubleshooting and repair in a unified time The repair test is OK. Go online at the specified time

Due to the limited developers and testers, bug repair must be carried out according to the situation and priority. After all, development and testing have other tasks

8. How many servers should we deploy and how much pressure should each server bear

The number of servers deployed depends on the actual situation of the project. Generally, users below 100000 will not use the cluster. The project has simple functions and will not use distributed services

At the initial stage of the company's project, in order to quickly develop an application iteratively, a server can be deployed at this time It is the best in terms of cost and efficiency

In the middle of the project, as the functions become more complex, the functional modules will be split. At this time, the deployment will be based on the number of module services and users

Current server situation of our company:

8000 + businesses, 1200 + daily businesses, 90w + users, 2w + daily businesses:

There are two servers on the PC # web side, three servers on the H5 # web side, one server for background management, one server for core services (processing various scheduled tasks), two upload servers, two SMS servers and two payment servers. The image server adopts Alibaba cloud OSS, the database adopts Alibaba cloud RDS mysql, and the cache adopts Alibaba cloud redis

There are many factors for the pressure on the server: the configuration of the server, the number of applications and performance are related. The server configuration of our company is 8 and 16G. This configuration can withstand more than 2000 concurrency

9. In actual development, when can a project be launched

The normal launch must pass the product and test. The product needs to determine whether the functions in the requirements have been realized. The test needs to determine whether the existing functions have no functional problems. The launch can only be launched after passing their acceptance project or new requirements

11 how much high concurrency can rabbitmq carry

How much high concurrency RabbitMQ can carry depends on the server performance. The concurrency of RabbitMQ on a 4-core 8G server can be broken by 1000

As long as you listen to the test students, not everyone will conduct performance test after all

12. Are database stored procedures useful in the project and what businesses are handled

MySQL 5.0} version supports stored procedures.

Stored Procedure is a database object that stores complex programs in a database for external programs to call.

Stored procedure is a set of SQL statements to complete specific functions. It is compiled, created and saved in the database. Users can call and execute it by specifying the name of the stored procedure and giving parameters (when necessary).

The idea of stored procedure is very simple, which is the code encapsulation and reuse at the level of database {SQL} language.

A stored procedure is a piece of code with a name, which is used to complete a specific function.

The created stored procedure is saved in the data dictionary of the database.


Stored procedures can be encapsulated and hide complex business logic.

Stored procedures can return values and accept parameters.

A stored procedure cannot be run using the SELECT instruction because it is a subroutine, unlike a view table, data table, or user-defined function.

Stored procedures can be used for data verification, enforcing business logic, etc.


Stored procedures are often customized to a specific database because the supported programming languages are different. When switching to the database system of other manufacturers, the original stored procedure needs to be rewritten.

The performance adjustment and writing of stored procedures are limited by various database systems.

Stored procedures are generally weak:

1. Limited by the database and programming language, each company has concerns when using it, and the subsequent migration and transformation costs will be great

2. The writing requirements are not as convenient as ordinary sql, and the familiar programming language is not used. The development efficiency is high

At present, stored procedures are not used in several projects I have been in

13. What are the methods for MySQL optimization and million level data processing

mysql Optimization:

Currently used:

1. It is forbidden to use 'select *' in actual development

2. When you know that there is only one row of data in the result, use # LIMIT 1. In this way, the MySQL database engine will stop searching after finding a piece of data, rather than continue to look up the next piece of data that matches the record.

3) index common search fields

4 always set an ID for each table as its primary key, and the best is an INT type (UNSIGNED is recommended) and set auto automatically added on it_ Increment flag.

5 like '%' in the front can't use the index, try to put '%' in the back for fuzzy query

6. MySQL} does not support function conversion, so you cannot add a function in front of the field, otherwise the index will not be used

7. Field type conversion leads to no index, such as no quotation marks for string type, quotation marks for number type, etc., which may lead to full table scanning without index

8. When the amount of data is large, it is necessary to divide the database and table

Online recommendations include:

1. Use a similar type of example in the Join table and index it: when the Join fields in the two tables have been indexed, MySQL will start the mechanism to optimize the SQL statement of the Join for you

2. Never use ORDER BY RAND(), which will only make the performance of your database decline exponentially

3. Use "ENUM" instead of "VARCHAR"

4. Try to use "union" instead of "Innodb" for the query of "or"

5. Try to avoid judging the "null" value of the field in the "where" clause, otherwise the engine will give up using the index and scan the whole table

6. Try to avoid using it in the where clause= Or < > operator, otherwise the engine will give up using the index and perform a full table scan

7. Try to avoid using "or" to join conditions in the "where" clause. If a field has an index and a field has no index, the engine will give up using the index and scan the whole table

8 in , and , not in , should also be used with caution, otherwise it will lead to full table scanning


Of course, if you want to analyze whether a statement needs to be optimized, you must use the Explain keyword to get suggestions from {procedure analysis()


Thousands and millions of data processing methods:

When the data reaches the level of millions, the efficiency of query is a big problem. At this time, after writing the sql statement, you should use explain to view the query information of the next statement and run the next statement to see the use time

When the efficiency is very low, it must be optimized:

1. Optimize the performance of statements -- the above optimization methods can be used

2. Optimize the table structure. Common problems are

A) Split the table fields, such as commodity table, commodity name, main drawing, specification and other unchanged fields into the basic information table, and the real-time information of commodities into the subsidiary table;

B) Split the large table by time, such as the user table. Put the users who have not logged in within the specified time (60 days) into a user freeze table, and the others in the user table. When the users in the freeze table log in again, move them to the user table

3. Upgrade from hardware

The first two are to reduce the amount of scanning (query) of statements, and the latter is to improve the performance and efficiency of scanning (query)

14. What if the Oracle index fails

1. Select the appropriate Oracle optimizer

2. Rebuild index: alter index name rebuild [online]

3. Force Index: after adding hint to the statement, force it to use the specified index

15 jvm parameter tuning

There are three restrictions on the maximum heap size in the JVM}:

a. Data model (32-bt or 64 bit) limitation of relevant operating system;

b. Available virtual memory limit of the system;

c. The available physical memory limit of the system.

Under 32-bit system, it is generally limited to 1.5G~2G; 64 is the operating system, which has no limit on memory.

Common configuration summary

Heap settings

-Xms: initial heap size

-Xmx: maximum heap size

-Xmn: young generation size

-Xss: virtual machine stack size per thread

-20: Newsize = n: set the size of the younger generation

-20: Newratio = n: sets the ratio of the younger generation to the older generation. For example, if it is 3, it means that the ratio of the young generation to the old generation is 1:3, and the young generation accounts for 1 / 4 of the sum of the young generation and the old generation

-20: Survivorratio = n: the ratio of Eden district to two survivor districts in the young generation. Note that there are two in the survivor area. For example, 3 means Eden: Survivor=3:2, and one survivor area accounts for 1 / 5 of the whole young generation

-20: Maxpermsize = n: set persistent generation size

-20: Maxtenuringthreshold = n: sets the maximum age of garbage. If it is set to 0, the younger generation objects will directly enter the older generation without passing through the Survivor area

Collector settings

-20: + useserialgc: set serial collector

-20: + useparallelgc: set parallel collector

-20: Parallelgcthreads = 20: configure the number of threads of the parallel collector, that is, how many threads are garbage collected at the same time. This value is preferably configured equal to the number of processors

-20: + useparalleloldgc: configure the old generation garbage collection method as parallel collection

-20: + useparalleldeloldgc: set parallel generation collector

-20: + useconcmarksweepgc: set concurrent collector

-20: Maxgcpausemillis = 100: set the maximum time for each garbage collection of the younger generation. If this time cannot be met, the JVM will automatically adjust the size of the younger generation to meet this value.

-20: + useadaptive sizepolicy: after this option is set, the parallel collector will automatically select the size of the younger generation area and the corresponding proportion of the Survivor area to reach the minimum corresponding time or collection frequency specified by the target system. This value is recommended to be turned on all the time when using the parallel collector.

-20: + disableexplicitgc. This parameter is used to prohibit the display of calling GC in the code

Garbage collection statistics





-20: Gctimeratio = n: set the percentage of garbage collection time in program running time. The formula is 1/(1+n)

-20: + printgcapplicationcocurrenttime: print the uninterrupted execution time of the program before each garbage collection

-20: + printgcapplicationsstoppedtime: the time when the program pauses during print garbage collection.

-20: Printheapatgc: print detailed stack information before and after GC

-Xloggc:filename: used in conjunction with the above to record relevant log information to a file for analysis.

Concurrent collector settings

-20: + cmsincrementalmode: set to incremental mode. It is applicable to the case of single CPU.

-20: + useparnewgc: set the younger generation to parallel collection. It can be used simultaneously with CMS collection. JDK5. Above 0, the JVM will set it by itself according to the system configuration, so there is no need to set this value.

-20: Cmsfullgcsbeforecompaction: since the concurrent collector does not compress and tidy the memory space, it will generate "fragments" after running for a period of time, reducing the operation efficiency. This value sets how many times GC is run to compress and tidy the memory space.

-20: + usecmcomportatfull collection: turn on compression for older generations. Performance may be affected, but fragmentation can be eliminated

Tuning summary

Young generation size selection

Application with priority to response time: set it as large as possible until it is close to the minimum response time limit of the system (select according to the actual situation). In this case, the frequency of young generation collection is also the smallest. At the same time, reduce the number of objects reaching the elderly.

Throughput priority applications: set as large as possible to reach Gbit. Because there is no requirement for response time, garbage collection can be carried out in parallel, which is generally suitable for applications with more than 8CPU.

Generation size selection

Response time priority applications: older generations use concurrent collectors, so their size needs to be set carefully. Generally, some parameters such as concurrent session rate and session duration should be considered. If the heap setting is small, it can cause memory fragmentation, high recovery frequency and application pause, and use the traditional mark clearing method; If the heap is large, it takes a long time to collect. The optimized scheme generally needs to be obtained by referring to the following data:

Concurrent garbage collection information

Concurrent collection times of persistent generation

Traditional GC information

Proportion of time spent on recycling of younger and older generations

Reducing the time spent by young and old generations will generally improve the efficiency of application

Throughput first applications: generally, throughput first applications have a large younger generation and a smaller older generation. The reason for the long-term storage of objects is to reduce the long-term storage of objects, so that most objects can be recycled as much as possible.

Fragmentation problems caused by smaller heaps

Because older generations of concurrent collectors use marking and cleaning algorithms, the heap will not be compressed. When the collector reclaims, it will merge the adjacent space so that it can be allocated to larger objects. However, when the heap space is small and runs for a period of time, there will be "fragmentation". If the concurrent collector cannot find enough space, the concurrent collector will stop, and then use the traditional marking and cleaning methods for recycling. If "fragmentation" occurs, the following configuration may be required:

-20: + usecmcomportatfull collection: enables compression of older generations when using concurrent collectors.

-20: Cmsfullgcsbeforecompaction = 0: when the above configuration is enabled, set the number of full GCS here to compress the older generation

Classic case:

java -Xmx3550m -Xms3550m -Xmn2g -Xss128k

-Xmx3550m: set the maximum available memory of the JVM to 3550M.

-Xms3550 M: set the JVM memory to 3550 M. This value can be set to the same value as - Xmx to avoid the JVM reallocating memory after each garbage collection.

-Xmn2g: set the size of the younger generation to 2G. Memory size of the entire JVM = size of the younger generation + size of the older generation + size of the persistent generation. The permanent generation is usually fixed at 64m, so increasing the young generation will reduce the size of the old generation. This value has a great impact on the system performance. Sun officially recommends that it be configured as 3 / 8 of the whole heap.

-Xss128k: set the virtual machine stack size of each thread. JDK5. After 0, the stack size of each thread is 1M, and before, the stack size of each thread was 256K. More applicable threads need to adjust the memory size. Under the same physical memory, reducing this value can generate more threads. However, the operating system still has a limit on the number of threads in a process, which cannot be generated indefinitely. The empirical value is about 3000 ~ 5000.

java -Xmx3550m -Xms3550m -Xss128k -XX:NewRatio=4 -XX:SurvivorRatio=4 -XX:MaxPermSize=16m -XX:MaxTenuringThreshold=0

-20: Newratio = 4: set the ratio of the younger generation (including Eden and two Survivor areas) to the older generation (excluding the persistent generation). If it is set to 4, the ratio of the younger generation to the older generation is 1:4, and the younger generation accounts for 1 / 5 of the whole stack

-20: Survivorratio = 4: set the size ratio of Eden area and Survivor area in the young generation. If it is set to 4, the ratio of two Survivor areas to one Eden area is 2:4, and one Survivor area accounts for 1 / 6 of the whole young generation

-20: Maxpermsize = 16m: set the persistent generation size to 16m.

-20: Maxtenuringthreshold = 0: sets the maximum age of garbage. If it is set to 0, the younger generation objects will directly enter the older generation without passing through the Survivor area. For applications with more elderly generations, efficiency can be improved. If the Survivor value is set to be larger in the younger generation, the Survivor value can be increased in the younger generation.

16. Spin lock and distributed lock

What is spin lock? It proposes a locking mechanism to protect shared resources.

In fact, spinlocks are similar to mutually exclusive locks. They are all used to solve the mutually exclusive use of a resource. Whether it is a mutex lock or a spin lock, at most one holder can hold the lock at any time, that is, at most one execution unit can obtain the lock at any time. However, they are slightly different in scheduling mechanism. For mutex, if the resource has been occupied, the resource applicant can only enter the sleep state. However, the spin lock will not cause the caller to sleep. If the spin lock has been held by other execution units, the caller will always cycle there to see whether the holder of the spin lock has released the lock. Therefore, the word "spin" is named.

Spin lock is a relatively low-level original way to protect data structures or code fragments. This kind of lock may have two problems:

Deadlock. Trying to recursively obtain a spin lock will inevitably cause a deadlock: the holding instance of the recursive program loops in the second instance to try to obtain the same spin lock, which will not be released. Using spinlocks in recursive programs should follow the following strategy: recursive programs must not call themselves when holding spinlocks, nor should they attempt to obtain the same spinlocks when calling recursively. In addition, if a process has locked the resource, even if other processes applying for the resource keep crazy "spin", they will not be able to obtain the resource and enter the dead cycle.

Too much cpu resources. If there is no restriction, because the applicant has been waiting in a cycle, the spin lock will not sleep if it is unsuccessful, and will continue to try. When a single cpu is used, the spin lock will make other process es unable to move Therefore, the general spin lock implementation will have a parameter to limit the maximum number of continuous attempts After exceeding the limit, the spin lock discards the current time slice Wait for the next chance.


Distributed lock is a way to control synchronous access to shared resources between distributed systems. In distributed systems, it is often necessary to coordinate their actions. If different systems or different hosts of the same system share one or a group of resources, when accessing these resources, they often need to be mutually exclusive to prevent interference with each other to ensure consistency. In this case, distributed locks need to be used.

At present, redis is generally used to implement distributed locks. The core code is:




17. Single sign on principle

Single Sign On (SSO for short). In multiple application systems, users only need to log in once to access all mutually trusted application systems.

There is an independent authentication center. Only the authentication center can accept the user's user name, password and other information for authentication. Other systems do not provide login access, but only accept the indirect authorization of the authentication center. Indirect authorization is realized by token. When the user name and password provided by the user are authenticated by the authentication center, the authentication center will create an authorization token. In the next jump process, the authorization token is sent to each subsystem as a parameter. When the subsystem gets the token, it gets the authorization, and then creates a local session


Features: one login, shuttle everywhere

18. From the front end to the database and then to the front end of the whole system, what problems are usually considered in code optimization and structure optimization

1. Time consuming of the request

2. Number of requests

3. Number of queries

4. Time consuming of query

5. Time consuming of code running

6. Code performance

7. Code coupling

8. Code readability

In short: optimization must be considered from the following aspects

Performance: such as code time-consuming, request response speed, number of requests, number of queries, query time-consuming

Maintainability: such as code coupling, readability and maintainability

19. How to prevent the interface from being exposed and others from maliciously brushing the interface with tools

Common ways:

1. Graphic verification code, which is often used for the protection of SMS interface

2. Limit the number of requests, which is common in second kill, rush purchase and other functions

3. Restrictions on process conditions, such as meeting certain conditions, registering users, obtaining permissions, etc

4. The ip address is limited. Generally, the write interceptor in java judges the unified ip. The same ip can only be accessed for a specified number of times within a specified time

5. Server interface verification: it is common for some interfaces that need to be paid. This kind of interface requires an internal token or secret key to request

20. What's the matter with dirty data?

Dirty reading means that when a transaction is accessing data and modifying the data, but the modification has not been committed to the database, another transaction also accesses the data and uses the data. Because the data is uncommitted, the data read by another transaction is dirty data, and the operation based on the dirty data may be incorrect.

Extension: non repeatable reading refers to reading the same data multiple times in a transaction. When this transaction is not finished, another transaction also accesses the same data. Then, between the two data reads in the first transaction, the data read in the first transaction may be different due to the modification of the second transaction. In this way, the data read twice in a transaction is different, so it is called non repeatable reading

21. What are the hazards of dirty data?

Dirty data is almost fatal when it comes to important data such as historical data and funds.

For example, in the second kill system, the generation of dirty data may lead to insufficient inventory and businesses will lose money; In the fund system, if there is dirty data, it will lead to the error of account consolidation of the whole system.

22. How to check the bug s online

For online projects, bug s are usually checked through the log system. Therefore, there must be detailed log records in the project. Before and after updating data, important operation nodes should have detailed log records.

23. How to handle exceptions in the project

There are only two ways to handle exceptions in a project:

1 try catch # grab exception

2) throw exception

The method is simple, but it pays attention to many details:

1. Runtimeexceptions that can be evaded by pre check should not be handled by catch, such as IndexOutofBoundsException (corner mark offside exception) and NullPointException (null pointer exception)

2. Exceptions cannot be used for process control or condition control: the efficiency of exceptions is much lower than that of comparative judgment

3. When trying to catch, you can't include all the bar codes in one brain, which will only increase the difficulty of problem location, making the code unable to deal with different exceptions. At the same time, it is also irresponsible

4. The purpose of catching exceptions is to handle them. If they are not handled, they should be thrown to their callers. It must be disposed of before being displayed to users

5. If there is a transaction code in the try catch, be sure to pay attention to whether the rollback transaction is required after the catch

6. When closing the resource object and stream object in the finally code block, try catch if there is any exception

7. The caught exception and the thrown exception type should match exactly, or the caught exception is the parent class of the thrown exception

8. finally, there can be no return in the code block: when there is a return, the return in try catch will not be executed

24. How to handle the project log, how to track online problems, and where the log exists

At present, log4j is used in online logs. debug level information will be recorded during testing, and info level information will be recorded when online. Generally, you need to log before and after updating database data, and sensitive operation nodes also need to log These logs are written to the log file and saved. Generally, the log file is saved for 7 to 15 days

Track online issues:

1. First determine which page or function the problem is in, and then check the log file corresponding to the function to see if there is Error information or Exception information

2. If there is no abnormal information, it is likely to be a problem of code logic. Check the function log to see the log. Generally, it can locate the problem point

3. If it cannot be located from the log, it can only be the duplicate disk function code

Storage of logs:

Logs on a single server generally exist in the specified directory and can be defined in log configuration

Distributed / clustered: it can exist on various servers, or log servers can be used to manage log files uniformly

25. How to interact with the test

The responsibility of testing is to find out the problems existing in the project application and submit them to the development and repair in time Find out and deal with the problems as much as possible before going online Now many developers feel that testing is the opposite of them, often tit for tat and shirk the problem In fact, testing and development are to improve the project functions as much as possible and deliver them to users, which is their common purpose

The interaction with the test should pay attention to the objective facts, check the causes according to the problems submitted by the test, and then solve the problems. If there are no problems, feed back to the test and retest The key point is to communicate more with the tester and understand each other's ideas, so as not to cause misunderstanding and affect the work

At least the development and testing of our company are very harmonious now. When we encounter urgent problems that need to be solved immediately during testing every day, we will communicate with the development immediately. Whether there are real problems will be solved by the development after troubleshooting Non urgent problems will be submitted to Zen, and developers will see and solve their own problems Test the bug resolution rate of Zen every day, and remind the development to solve the bug

27 what is the process of bug handling

Problem feedback: test or user feedback

Problem determination: after the developer gets the problem, the problem will be reproduced in the test suit. If it cannot be reproduced, the problem can be located by checking the log and redoing the code

Problem solving: generally, small problems will be repaired on the trunk and tested online, and major problems will be repaired by opening branches. After the test is no problem, they will be combined and tested online

Notice: after the problem is solved and put online, notify relevant departments and personnel of the repair results (achieve results in everything)

26. How to deploy the project

At present, java projects are generally deployed on tomcat. After springboot appears, the project is directly packaged into jar s and run.

Confirm the environment before deployment: confirm whether the environment required by the project application is correct, such as system environment, java version, database version and system hardware configuration

Confirm the project configuration file: some project configuration files need to be modified during testing. At this time, they need to be changed back when going online. If there is no check, the test configuration may be used to go online, which will lead to problems on going online

Confirm the database table fields: prevent errors from being reported after going online because the newly added tables or fields are not added or the names are different

Confirmation and notification of online time

Back up the previous online code when online: ensure that you can go back when online fails

After online: the online functions must be tested again to prevent problems

28. What bug s have you encountered in the development of your mall

1. Concurrent and repeated data requests often occur when distributed locks are not made: add distributed locks

2. When the user touches the interface of second kill rush purchase, use the tool to submit rush purchase repeatedly: use the interceptor to limit the request interval of the same ip and the same interface

3. Data abnormality caused by multiple logins of one user: restrict users to log in only once

4. The database is emptied: Fortunately, the database data is backed up every hour. Import the backup data back to the database on the line, but still lose the data after the backup point

5. The system reaches the bottleneck: upgrade the hardware configuration and use the cluster

29. How do you make the order? What is the realization idea

At present, I have encountered two implementation methods:

1. When a user purchases a commodity, an order record is generated, and the inventory of the commodity is reduced by one

2. Generate inventory quantity tokens when publishing goods. Each time a user purchases goods, they will get a token and generate an order record. The tokens will become invalid after they are used

The first one needs to pay attention to repeated submission and concurrency

The second is applicable to applications with small commodity inventory

30, how do you do it? How to ensure safety with Alipay and WeChat?

The docking process between WeChat and Alipay has corresponding processes, and they provide detailed docking demo.. The docking of these two payment methods and fast money payment methods are basically the same


When the user initiates a payment request, the application server will add the amount to be paid, the reason for payment and the unique merchant order number generated by the application using the addition method provided by the payment interface party, produce the pre payment record, and colleagues call the payment interface for payment There are two ways to obtain receipt after payment submission: synchronous and asynchronous Synchronization refers to that the user clicks to complete the payment, and the server initiates the query like the payment interface server to verify the query results Asynchrony refers to the successful payment request that the payment interface party applies to the specified interface after receiving the payment and payment. We analyze and verify the request No matter asynchronous or synchronous, the unique merchant order number generated by us will be returned as a receipt After the operation is successful, update the record according to the merchant order


Security: all these payment methods will have a signing step when submitting payment. When the corresponding payment is completed, their server will call back our interface At this time, we use the specified key and countersignature method for their request parameters, and verify the countersignature results

31. What if the user orders the goods in the shopping cart at the same time on the mobile phone and PC

Lock the goods in the shopping cart. Only the party who gets the lock can place an order, and the other party cannot place an order

32. How to ensure that the user's data is secure after logging in and that the user's data will not be intercepted by a third party

Now we deal with:

Encryption is generally a symmetric encryption method

2. Replace the information with special characters, such as mobile phone number: replace the middle digits of the mobile phone number with * at the server



SVN is an open source version control system. Through the efficient management of branch management system, in short, it is used for multiple people to jointly develop the same project, share resources and realize the final centralized management.

basic operation

Upload local items to SVN

Project name - > right click - > team - > Share Project

Common operation



compare with ...

replace with ...

Conflict handling

  • Update - > handle conflict code - > commit
  • Merge conflict code when synchronizing SVN - > mark as merge - > commit
  • Try to avoid this method (local code - > backup - > with commit)


Overview of trunk, tags and branches




  ---- trunk

  |      |

  |      ---- AnalyzeDataView

  |      ---- LogCollection


  ---- tags

  |      |

  |      ---- AnalyzeDataView_release_1.0


  ---- branches


         ---- AnalyzeDataView_bugfix_1_0


Trunk: for trunk development
tags: used for labeling and archiving directory. It cannot be modified
branches: used for branch development, Bug repair, branch function point development, etc

Another project structure

ProjectA -> trunk -> ProjectA

         -> tags

                  -> tag_release_1.0

                  -> tag_release_1.0.1


                  -> branch_bugfix_1.0

svn # common commands

#Get the version of the specified date

svn co svn:// -r "{20160512}"

svn co --username XXX --password XXX



13.Crawler, single sign on, eight level linkage, scheduling


Because in the project I participated in, for the needs of marketing, in order to obtain the latest XXXX information, we made a relatively simple web crawler in Python language, which is specially used to climb the latest hot search on Sina Weibo and give it to the employees of the marketing department as a reference.


Single sign on (SSO):

In addition, because our project is divided into multiple systems, in order to solve the problem of repeated login caused by cookie failure across domains, we use token technology to realize single sign on.


Eight level linkage:

For the project I participated in, when filling in the receiving address after shopping, we need to select the detailed address. We use the multi-level linkage of the drop-down menu, that is, we create multiple tables. The secondary id of each sub table is the id of the parent table. Finally, we achieve eight levels of linkage.



In order to solve the regular announcement and transaction in the project, we use the Quartz task schedule management system, such as publishing the whole station announcement and mall information on time, and running a piece of code at the specified time.



In this project, we use shiro security framework to manage user login and resource permission control.

Implementation details: after the user clicks login, the user information will be encapsulated into a token to call subject The login () method submits the authentication, and shiro's securityManager security manager will call Authenticator to execute the authentication, and call the token of realm (the realm class needs to implement the authorizing realm interface to rewrite the authentication and authorization methods) The getprincipal () method obtains the user name and password, compares the password with the password of the user in the database, and returns the AuthenticationInfo authentication information if the authentication is successful; This information includes identity and credentials; If the verification fails, the corresponding AuthenticationException implementation will be thrown. If the login is successful, the corresponding menu permission will be obtained according to the current login user, and the user's permission will be granted in realm. Call the hasRole of realm to determine whether the current user has this role permission. isPermitted is provided by shiro framework to judge whether it has a certain permission or all permissions, load different menus or perform different operations according to different permissions.


kafka: receive java Log queue of messages posted by the program
logstash: Log parsing, formatted data as json And output to es in
elasticsearch: Real time search engine, storing data
kibana: be based on es Data visualization component, query data
ELK+kafka Principle of log system (the medium is log)
Windows/linux of logstash((client)--->kafka(Queue)--->kakfa Upper logstash((also a client)--->ES((storage)--->kibana(Interface)
The core is logstash Configuration file for




In the * * * * project, the website needs to display the weather of each city to improve the user experience.

After consideration, the project team chose to call the weather services of other websites through the third-party webservice service. Based on this, we check the service description to understand the supported service interfaces.

In the development and testing phase, we Automatically generate client code with the help of wsimport command tool.

The WebService process is: first, obtain the ID corresponding to the city through three-level linkage, and import the required dependent packages.

When the user's request information for querying the city arrives at the system, the system sends the information of the corresponding city to the webService through the third-party interface and receives the processing results

Parse the json object returned by webService to the foreground and display the processing results through ajax and fastjson

17.reflex,report form

JAVA Reflection in is the ability of a running program to check itself and the software running environment. It can be changed according to what it finds. Generally speaking, reflection can obtain class information according to the specified class name at run time.
First, we define two concepts, static compilation and dynamic compilation.
Static compilation: determine the type and bind the object during compilation,That is, through. Dynamic compilation: determine the type and bind objects at runtime. Dynamic compilation maximizes java The flexibility of reflects many    The application of state can reduce the coupling between classes.   
We can clearly see the benefits of dynamic compilation, and reflection is the use of dynamic compilation to create objects.
A report is a collection of information in a project excel It can be exported in the form of and used by the customer's finance or our operation and maintenance personnel.
Of course, the report module uses a tool class Jcreporter,It can be called directly. For example, there are other methods commonly used for report making poi. 
mybatis paging:First, first maven Import in jar package<dependency>
Then in spring.xml Medium configuration
 <!--to configure sqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--Configure alias-->
        <property name="typeAliasesPackage" value="cn.entity"/>
        <property name="plugins">
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
Finally, perform paging operation directly and create a return value of pageinfo Interface of
 //Paging query
    public PageInfo<HouseVo> selectByPage(Integer pageNum, Integer pageSize) {
        //Paginate the following query startPage(pageNum,pageSize);
        List<HouseVo> list = mapper.selectByPage();
        return new PageInfo<HouseVo>(list,4);


18.ELK+Kafka log collection environment construction

1. Build Elasticsearch environment and test:
(1) delete es container
(2) delete the image of es
(3) host machine memory adjustment: execute the command: sudo sysctl - W VM max_ map_ count=655360
(4) modify docker compose through ftp software MEM in YML_ limit: 2048M
(5) find the virtual machine and execute the command: CD / home / PX2 / envdm / springcloudv2 0/
Execute the command: docker compose up - D elasticsearch
(6) test es: The version number of ES indicates that the configuration of the environment is successful.

2. Build logstash
(1) open logstash in the material
Step: enter the container of logstash
  vi /usr/local/logstash-6.3.0/config/logstash. YML (modify the IP of the connection es)
Amend to read: ""
  xpack.monitoring.elasticsearch.username: elastic
  xpack.monitoring.elasticsearch.password: changeme
  xpack.monitoring.enabled: false

  (2)vi /usr/local/logstash-6.3.0/bin/logstash.conf
Modify ip and add log parameters
      bootstrap_servers => [""]
      group_id => "test-consumer-group"
      auto_offset_reset => "latest"
      consumer_threads => 5
      decorate_events => true
      topics => ["dm"]
      type => "bhy"

  output {
      hosts=> [""]
      index=> "dmservice-%{+YYYY.MM.dd}"
      codec => json_lines

3. Modify kibana configuration file
(1) find elasticsearch URL: and modify it to“ "
(2) visit: If there is no es data, it indicates success.

(1) find the server properties

(2) start kafka command
  ./ --bootstrap-server --topic dm --from-beginning


19.What is mycat? How do you understand? What are the segmentation rules of your company's sub database and sub table? What are the commonly used configuration files for building mycat environment?

1. What is mycat?

The most active and best performance open source database sub database and sub table Middleware in China

  • A completely open source large database cluster for enterprise application development
  • Support transaction, ACID and enhanced database that can replace MySQL
  • An enterprise database that can be regarded as a MySQL Cluster is used to replace the expensive Oracle cluster
  • A new SQL Server integrating memory cache technology, NoSQL technology and HDFS big data
  • A new generation of enterprise database products combining traditional database and new distributed data warehouse
  • A novel database middleware product

2. Slice rule: take mold

<tableRule name="mod-long">
    </rule></tableRule><function name="mod-long" class="io.mycat.route.function.PartitionByMod">
    <!-- how many data nodes -->
    <property name="count">3</property></function>

Configuration Description:
|Label attribute | description|
| --------- | -------------------- |
|columns | identifies the table field to be fragmented|
|algorithm | piecewise function|
|count | number of slices|

Calculate the decimal module budget according to the id.

3. Build common configuration files for mycat environment



<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mycat:rule SYSTEM "rule.dtd"><mycat:rule xmlns:mycat="http://io.mycat/">
     <tableRule name="auto-sharding-rang-mod-order">
    </rule></tableRule><function name="rang-mod-dm"  class="io.mycat.route.function.PartitionByMod">
    <property name="count">3</property></function></mycat:rule>


<?xml version="1.0"?><!DOCTYPE mycat:schema SYSTEM "schema.dtd"><mycat:schema xmlns:mycat="http://io.mycat/">
    <schema name="dm_order"  checkSQLschema="true" sqlMaxLimit="100">
       <table name="dm_order" primaryKey="id" autoIncrement="true" dataNode="dn1,dn2,dn3"
    <dataNode name="dn1"   dataHost="a"  database="dm_order1"/><dataNode name="dn2"   dataHost="a"  database="dm_order2"/><dataNode name="dn3"   dataHost="a"  database="dm_order3"/><dataHost  name="a"   maxCon="1000"  minCon="10"  balance="0"
    writeType="0"   dbType="mysql"
        dbDriver="native" switchType="1"  slaveThreshold="100">
    <heartbeat>select 1</heartbeat>
    <writeHost host="hostM1"
        url="" user="root" password="123456">


<?xml version="1.0" encoding="UTF-8"?><!-- - - Licensed under the Apache License, Version 2.0 (the "License"); 
    - you may not use this file except in compliance with the License. - You 
    may obtain a copy of the License at - - 
    - - Unless required by applicable law or agreed to in writing, software - 
    distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 
    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the 
    License for the specific language governing permissions and - limitations 
    under the License. --><!DOCTYPE mycat:server SYSTEM "server.dtd"><mycat:server xmlns:mycat="http://io.mycat/">
    <property name="useSqlStat">0</property>  <!-- 1 To enable real-time statistics, 0 to disable -->
    <property name="useGlobleTableCheck">0</property>  <!-- 1 To enable all overtime consistency detection and 0 to close -->
        <property name="sequnceHandlerType">2</property>
      <!--  <property name="useCompression">1</property>--> <!--1 For on mysql Compression protocol-->
        <!--  <property name="fakeMySQLVersion">5.6.20</property>--> <!--Set simulated MySQL Version number-->
    <!-- <property name="processorBufferChunk">40960</property> -->
    <property name="processors">1</property> 
    <property name="processorExecutor">32</property> 
        <!--Default to type 0: DirectByteBufferPool | type 1 ByteBufferArena-->
        <property name="processorBufferPoolType">0</property>
        <!--The default is 65535 64 K be used for sql Maximum text length during parsing -->
        <!--<property name="maxStringLiteralLength">65535</property>-->
        <!--<property name="sequnceHandlerType">0</property>-->
        <!--<property name="backSocketNoDelay">1</property>-->
        <!--<property name="frontSocketNoDelay">1</property>-->
        <!--<property name="processorExecutor">16</property>-->
            <property name="serverPort">8066</property> <property name="managerPort">9066</property> 
            <property name="idleTimeout">300000</property> <property name="bindIp"></property> 
            <property name="frontWriteQueueSize">4096</property> <property name="processors">32</property> -->
        <!--Distributed transaction switch: 0 means not filtering distributed transactions, 1 means filtering distributed transactions (if only global tables are involved in distributed transactions, then not filtering), and 2 means not filtering distributed transactions,However, distributed transaction logs are recorded-->
        <property name="handleDistributedTransactions">0</property>
            off heap for merge/order/group/limit      1 open   0 close
        <property name="useOffHeapForMerge">1</property>
            The unit is m
        <property name="memoryPageSize">1m</property>
            Unit is k
        <property name="spillsFileBufferSize">1k</property>
        <property name="useStreamOutput">0</property>
            The unit is m
        <property name="systemReserveMemorySize">384m</property>
        <!--Whether to adopt zookeeper Coordinated switching  -->
        <property name="useZKSwitch">true</property>
    <!-- overall situation SQL Firewall settings -->
          <host host="" user="mycat"/>
          <host host="" user="mycat"/>
       <blacklist check="false">
    <user name="root">
        <property name="password">123456</property>
        <property name="schemas">dm_order</property>
        <!-- Table level DML Permission setting -->
        <privileges check="false">
            <schema name="TESTDB" dml="0110" >
                <table name="tb01" dml="0000"></table>
                <table name="tb02" dml="1111"></table>


20.What is the relationship between SpringBoot and SpringCloud?

SpringBoot: focus on the rapid and convenient development of individual micro services (focusing on micro);
SpringCloud: a microservice coordination and governance framework that focuses on the overall situation, and combines and manages individual microservices developed by SpringBoot (focusing on the macro);
SpringBoot can be used independently of SpringCloud, but SpringCloud cannot leave SpringBoot, which belongs to dependency.

21.Authority management

Permission management is the security category of the system. It requires that a legitimate user can access the system (user authentication), and must have the access permission of the resource to access the resource (authorization).

Authentication: verification of the legal identity of users. Only legal users can access the system.

Authorization: access control. You must have the access permission of the resource to access the resource.


Permission model: the standard permission data model includes: user, role, permission (including resources and permissions), user role relationship and role permission relationship.

Permission assignment: it is convenient to assign permissions to users through the UI interface, and add, delete, modify and query the upper permission model.

Permission control:

Role based permission control: determine whether there is operation permission according to the role, because the role is highly changeable. If the role modification needs to modify the control code, the system scalability is not strong.

Resource based permission control: judge whether there is operation permission according to the resource permission, because the resources are relatively fixed. If the role modification or permission modification in the role does not need to modify the control code, this method has strong maintainability. Recommended use.


Solutions for rights management:

n. for coarse-grained permission management, it is recommended to solve it at the system architecture level and write the system architecture level unified code (basic code).

Coarse grained permissions: for example, manage the system's URLs, menus, jsp pages, buttons on pages and class methods, that is, manage the resource types.


n. for fine grain permission management:

Coarse grained permission: for example, user information with user id 001 (resource instance) and commodity information with type t01 (resource instance), manage the permission of resource instances and understand the permission management of data level.

Fine grained permission management is the business logic of the system. The business logic code is not convenient to extract the unified code. It is recommended to deal with it at the business layer of the system.


url based rights management (Master):

The commonly used method of enterprise development is realized by using the filter in the web application. The user requests the url and intercepts it through the filter to judge whether the user's identity is legal (user authentication) and whether the requested address is the url (authorization) within the user's authority.



shiro is a rights management framework and an open source project under apache. Compared with the spring security framework, it is simpler and more flexible, and spring security relies heavily on spring. shiro can realize the authority management of web system, c/s, distributed system and so on.


shiro certification process: (Master)

1. Subject requests authentication and calls subject login(token)

2. The securitymanager performs authentication

3. The SecurityManager is authenticated by the ModularRealmAuthenticator.

4. The ModularRealmAuthenticator transmits the token to realm, which queries the user information (including identity and credentials) from the database according to the user information in the token

5. If the user cannot be queried, null will be returned to the ModularRealmAuthenticator, and the ModularRealmAuthenticator will throw an exception (the user does not exist)

6. If the user is queried, return the authenticationinfo (authentication information) to the modular realm authenticator

7. The ModularRealmAuthenticator takes the authenticationinfo (authentication information) to compare the credentials (passwords). If they are consistent, the authentication is passed. If not, an exception will be thrown (voucher error).


Subject: subject


Authenticator: authenticator (provided by shiro)


Realm (generally customized): equivalent to the data source, the authenticator needs realm to query user identity information and permission information from the data source.


9. Problems of Java lock mechanism

  1. ABA problem

CAS can cause "ABA problems".

An important prerequisite for the implementation of CAS algorithm is to take out the data in the memory at a certain time, and compare and replace it at the next time, then the time difference class will lead to the change of data.

At this time, the thread takes out the data from two to V in the CAS, and then the thread takes out the data from two to V in the CAS. However, the operation is still successful, and then the thread takes out the data from two to V in the CAS. Although the CAS operation of thread one is successful, it does not mean that there is no problem in this process.

The realization of some optimistic locks is to solve the ABA problem through the version. Every time the optimistic lock modifies the data, it will carry a version number. Once the version number is consistent with the version number of the data, the modification operation can be performed and the + 1 operation can be performed on the version number, otherwise the execution will fail. Because the version number of each operation will increase, there will be no ABA problem, because the version number will only increase rather than decrease.


  1. CAS optimistic lock

CAS is an optimistic locking technology. When multiple threads try to use CAS to update the same variable at the same time, only one thread can update the value of the variable, while other threads fail. The failed thread will not be suspended, but will be told that it has failed in the competition and can try again.

The CAS operation consists of three operands -- memory location (V), expected original value (A), and new value (B). If the value of the memory location matches the expected original value, the processor automatically updates the location value to the new value. Otherwise, the processor does nothing. In either case, it returns the value of the location before the CAS instruction. (in some special cases of CAS, only the success of CAS will be returned without extracting the current value.) CAS effectively states that "I think position V should contain the value A; if it contains the value, put B in this position; otherwise, don't change the position, just tell me the current value of this position." This is actually the same principle as the conflict check + data update of optimistic lock.


  1. Implementation principle of synchronize

The synchronization code block is implemented by using the , monitorenter , and , monitorexit , instructions. The synchronization method (which can't be seen here and needs to see the underlying implementation of the JVM) relies on the , ACC on the method modifier_ Synchronized} implementation.


  1. The difference between synchronize and lock

Usage difference between synchronized and lock

Ossynchronized (hidden lock): add this control to the objects that need to be synchronized. Synchronized # can be added to the method or in a specific code block. The parentheses represent the objects that need to be locked.

olock (display lock): the specified start position and end position need to be displayed. Generally, the , ReentrantLock , class is used as the lock. One , ReentrantLock , class must be used as the object in multiple threads to ensure the effectiveness of the lock. In addition, the locking and unlocking positions need to be indicated through the display of {lock() and} unlock(). Therefore, it is common to write , unlock() in the , finally , block to prevent deadlock.

The performance difference between synchronized and lock , synchronized , is managed to the JVM for execution, while lock , is the code written by Java to control locks. In JDK 1.5, synchronize is inefficient. Because this is a heavyweight operation and needs to call the operation interface, it is possible that locking consumes more system time than other operations. In contrast, using the lock object provided by Java has higher performance. But by JDK 1.6, changes have taken place. Synchronize is semantically clear and can be optimized for spin adaptation, lock elimination, lock coarsening, lightweight lock, bias lock, etc. As a result, the performance of {synchronize} on {JDK 1.6} is no worse than that of {lock}.

The difference between synchronized and lock mechanisms

Ossynchronized # originally adopted the pessimistic locking mechanism of CPU, that is, the thread obtains the exclusive lock. An exclusive lock means that other threads can only rely on blocking to wait for the thread to release the lock.

oLock , uses optimistic locking. The so-called optimistic lock is to complete an operation without locking each time, assuming that there is no conflict. If it fails due to the conflict, try again until it succeeds. The mechanism of optimistic lock implementation is CAS operation (Compare and Swap).


  1. Principle of volatile implementation

At the bottom of the JVM, volatile is implemented by "memory barrier"

 cache consistency protocol (MESI protocol), which ensures that copies of shared variables used in each cache are consistent. Its core idea is as follows: when a CPU is writing data, if it finds that the operated variable is a shared variable, it will notify other CPUs that the cache line of the variable is invalid. Therefore, when other CPUs read the variable and find it invalid, they will reload data from main memory


  1. Business scenario and implementation of optimistic lock

Optimistic Lock:

 you won't worry about the data being modified every time you get the data, so you won't lock it every time you get the data, but you need to judge whether the data has been modified by others when updating the data. If the data is modified by other threads, the data will not be updated. If the data is not modified by other threads, the data will be updated. Because the data is not locked, the data can be read and written by other threads.

 it is more suitable for the scenario with frequent read operations. If there are a large number of write operations, the possibility of data conflict will increase. In order to ensure the consistency of data, the application layer needs to constantly re acquire data, which will increase a large number of query operations and reduce the throughput of the system.


  1. Talk about thread safety

Thread safety is a problem in the field of multithreading. Thread safety can be simply understood as that a method or an instance can be used in a multithreaded environment without problems.

In Java multithreaded programming, there are many ways to realize java thread safety:

 the simplest way is to use the Synchronization keyword

 use Java util. concurrent. Atomic class in atomic package, such as AtomicInteger

 use Java util. concurrent. Locks locks in the package

 use thread safe collection # ConcurrentHashMap

 use the "volatile" keyword to ensure variable visibility (read directly from memory rather than from thread cache)

Inster written test:

1. Difference between process and thread

There is at least one process under a program, at least one thread under a process, and multiple threads under a process to increase the execution speed of the program.


2. What is the impact of multithreading concurrency on the life cycle of threads

When a thread is created and started, it neither enters the execution state as soon as it is started, nor is it always in the execution state< Br > in the life cycle of a thread, it goes through five states: new, Runnable, Running, blocked and dead.

Impact of multithreading Concurrency:

When multithreading is concurrent, it will be unsafe. When multithreading operates on the attributes or states of objects at the same time, the information between threads is not synchronized, and the state read by thread A is outdated, but thread A does not know it.


3. Characteristics of queue and stack. In what actual cases?

Stack features: first in, last out, last in, first out

Characteristics of queue: first in first out, last in and last out


4. The function of synchro3ized. What other locks are commonly used in java?

synchronized # it can treat any non NULL object as a lock. It is an exclusive pessimistic lock and a reentrant lock.

1. When acting on a method, it locks the instance of the object (this);

2. When used as a static method, the Class instance is locked, and all threads calling the method will be locked;

When the synchronized object is a block of code that locks all objects.

Common locks in Java include optimistic lock, pessimistic lock and spin lock

  1. What is the difference between synchronized and volatile?

1.volatile essentially tells the jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from the main memory; synchronized locks the current variable. Only the current thread can access the variable, and other threads are blocked.

2.volatile can only be used at the variable level; synchronized can be used at the variable, method, and class levels

3.volatile can only realize the modification visibility of variables and cannot guarantee atomicity; synchronized ensures the visibility and atomicity of variable modification

4.volatile will not cause thread blocking; synchronized may cause thread blocking.

5. Variables marked volatile will not be optimized by the compiler; Variables marked synchronized can be optimized by the compiler

6. Scope and life cycle of spring Bean

Scope of Bean: singleton, prototype, request, session and global session

Bean's life cycle process:

1. First, after the container is started, the bean whose scope is singleton and not lazy loaded will be instantiated,

2. Inject all attributes according to Bean definition information and configuration information,

3. If the Bean implements the BeanNameAware interface, it will call back the setBeanName() method of the interface and pass in the id of the Bean. At this time, the Bean will obtain its own id in the configuration file,

4. If the Bean implements the BeanFactoryAware interface, it will call back the setBeanFactory() method of the interface and pass in the BeanFactory of the Bean, so that the Bean will get its own BeanFactory,

5. If the Bean implements the ApplicationContextAware interface, it will call back the setApplicationContext() method of the interface and pass in the ApplicationContext of the Bean, so that the Bean will get its own ApplicationContext,

6. If a Bean implements the BeanPostProcessor interface, it will call back the postprocessbeforeinitialization() method of the interface,

7. If the Bean implements the InitializingBean interface, it will call back the afterpropertieset() method of the interface,

8. If the Bean is configured with init method method, the method configured with init method will be executed,

9. If a Bean implements the BeanPostProcessor interface, it will call back the postProcessAfterInitialization() method of the interface,

10. After process 9, the Bean can be officially used. For a Bean with a singleton scope, an instance of the Bean will be cached in the ioc container of spring, while for a Bean with a prototype scope,

Each time it is called, a new object will be created, and the life cycle will be managed by the caller, which is no longer managed by the Spring container

11. After the container is closed, if the Bean implements the DisposableBean interface, it will call back the destroy() method of the interface,

12. If the Bean is configured with the destroy method method, the method configured with the destroy method will be executed. At this point, the life cycle of the whole Bean ends. four

7. Six common annotations and functions of spring


Configure the class. When using this annotation, SpringIOC will automatically scan this class into a bean instance

When not written, the default is the class name, and the initial letter is lowercase


Automatic assembly will find the specified bean according to the type. Required: indicates whether injection is required if the specified annotation cannot be found in the bean directory. The default is true. When it is modified to false, it indicates that injection is not allowed if it is not found.


Multiple xml files can be read, so that multiple xml defined bean s can be introduced


Marking on business layer components means defining a bean, and automatically instantiating a bean with lowercase initial according to the marked component name.


Used to transfer object parameters


It is used to automatically assemble beans and activate dependency injection of a named Resource@ The Resource name attribute can define the name of the automatically assembled Bean

  1. Explain what is a transaction, what problems will be caused by multithreaded transaction concurrency, and briefly describe the four isolation of transactions

Transactions are a series of strict operations in an application. All operations must be completed successfully, otherwise all changes made in each operation will be undone.

That is, transactions are atomic. A series of operations in a transaction are either all successful or none.

There are two ways to end a transaction. When all steps in the transaction are successfully executed, the transaction is committed. If one of the steps fails, a rollback operation will occur, undoing all operations from before to the beginning of the transaction.


Concurrency problems can be divided into the following categories:

A. Lost updates

B. Dirty reading

C. Non repeatable reading

D. Overwrite update

E. Virtual reading (unreal reading)


Four types of transaction isolation:

A.Serializable: a transaction cannot see the updates made by other transactions to the database during execution

(when a transaction is executed, other transactions are not allowed to execute concurrently. Transactions are executed serially, and transactions can only be executed one by one, not concurrently.).

B.Repeatable Read: during the execution of a transaction, you can see the newly inserted records committed by other transactions, but you can't see the updates of existing records by other transactions.

C. Read committed: during the execution of a transaction, you can see the newly inserted records committed by other transactions and the updates of existing records committed by other transactions.

D.Read Uncommitted: during the execution of a transaction, you can see the newly inserted records that other transactions have not committed, and you can see the updates to existing records that other transactions have not committed.

9. What is aop? Several notification methods of spring

aop is aspect oriented programming. In the whole system, adding new functions dynamically and horizontally does not change the programming of the original business process


Several notification methods of spring:

1. Pre notification (notification before method call)

2. Post notification (notify when the method returns normally after calling, and the return value can be obtained. It will not be executed in case of exception)

3. Final notice (it will be executed regardless of whether the program is abnormal or not)

4. Exception notification (execution in case of exception)

Execution time of notification (5)

10. Draw the memory operation diagram of jvm and explain its function

First, java source code files (. Java suffixes) will be compiled into bytecode files (. class suffixes) by the java compiler,

Then, the bytecode files of each class are loaded by the class loader in the JVM. After loading, they are handed over to the JVM execution engine for execution.

In the whole process of program execution, the JVM will use a space to store the data and related information needed during program execution,

This space is generally referred to as the Runtime Data Area, which is what we often call JVM memory.

Therefore, the memory management we often talk about in Java is to manage this space




  1. Handwriting quick sorting algorithm


The first sort: sorted(), natural sort


    public void test8() {

        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");;



The second sort: sorted(Comparator com) - customized sort

public void test8() {

        List<String> list = Arrays.asList("qqq","aaa","bbb","ccc","ddd");;,y) -> {

           if(x.getDeptno().equals(y.getDeptno())) {

               return x.getDname().compareTo(y.getDname());

           }else {

               return x.getLoc().compareTo(y.getLoc());




//The third sort by Map


//Create a Map and fill in the data


Map<String, Integer> codes = new HashMap<>();

codes.put("United States", 1);

codes.put("Germany", 49);

codes.put("France", 33);

codes.put("China", 86);

codes.put("Pakistan", 92);


//Sort by Map key

Map<String, Integer> sortedMap = codes.entrySet().stream()






        (oldVal, newVal) -> oldVal,





//Print the sorted Map


//Sort by value

  Map<String, Integer> sortedMap2 = codes.entrySet().stream()





            (oldVal, newVal) -> oldVal,



//Print after sorting




12. Handwriting thread safe singleton mode


//Lazy, thread safe

public class Singleton { 

    private static Singleton instance; 

    private Singleton (){} 

    public static synchronized Singleton getInstance() { 

      if (instance == null) { 

         instance = new Singleton(); 


    return instance; 




//Hungry Han style

public class Singleton { 

    private static Singleton instance = new Singleton(); 

    private Singleton (){} 

    public static Singleton getInstance() { 

      return instance; 




//Double checked locking (DCL), jdk1 5 cases

public class Singleton { 

    private volatile static Singleton singleton; 

    private Singleton (){} 

    public static Singleton getSingleton() { 

    if (singleton == null) { 

        synchronized (Singleton.class) { 

          if (singleton == null) { 

             singleton = new Singleton(); 




    return singleton; 




//Registered / static internal class

public class Singleton { 

    private static class SingletonHolder { 

    private static final Singleton INSTANCE = new Singleton(); 


    private Singleton (){} 

    public static final Singleton getInstance() { 

      return SingletonHolder.INSTANCE; 




//Enumeration, jdk1 5 cases

public enum Singleton { 


    public void whateverMethod() { 




Experience: Generally speaking, it is not recommended to use the lazy way, but the hungry way. Only when the lazy loading effect is to be clearly realized can it be used

Use the registration method. When it comes to deserialization and creating objects, you can try enumerating. If there are other special requirements, double inspection can be considered

Lock mode.

13. Design a structure diagram of second kill




Huawei headquarters interview:
It's mainly something at the bottom. The general topic of the two Huawei project teams today is.
① Basic data types and their packaging classes (mainly basic data types, why packaging classes, and what are the differences between basic data types and packaging classes as formal parameters)
② jvm's memory model [what are the common parts of threads that are private to threads, what are stored respectively, what is changed to the java8 method area (changed to the metadata area, and ask what is the difference between them), what is also called Java memory leakage (how to avoid memory leakage -- mainly the reference type of objects)], Garbage collection mechanism (the division between the new generation and the old generation, what recycling algorithms they use respectively, what are the common garbage collectors, what are their characteristics, and whether their garbage collectors are the same when running in client and server mode (what is called client, server mode, jit)). The second is very important. Both project teams asked
③ What is the difference between the underlying implementation of hashmap in 1.7 and 1.8, and what are the advantages of these improvements (as well as the extended bucket sorting (the fastest sorting, sacrificing memory and ensuring performance), the overall structure of red black tree and its four rules). The two project groups asked, and the second asked deeper.
④ How does spring ensure thread safety when creating objects through bean s
⑤ Because I wrote the difference between websocket, http and https in my project (mainly the encryption of the latter, what is the basis of his encryption), how to ensure that the information will not be forged, tampered with or intercepted when communicating between two people (mainly symmetric encryption and non symmetric encryption in reversible encryption, as well as their cooperation), There is also the certificate problem in the trust chain.
⑥ The difference between abstract classes and interfaces
⑦ What thread safe classes have you used? Why are they thread safe? If you are given a thread unsafe class, how can you change it to thread safe.
⑧ Build a rough vue
⑨ How to execute a method in a jar. (there is mainly a MANIFEST.MF file, where main class. Is configured, and then via java -jar abc.jar)
⑩ Recently, cpu and memory utilization of a server has suddenly increased. How to check it.
① Tell me about the specific implementation of single sign on
② I said I studied c and Java in college. He asked me that java8 has a new feature called lambda. What is its similarity with c language.

Green and:
1. How many years of working experience?

2 year


2. What framework is used?

spring boot Micro service architecture


3. Is the front and rear ends separated

Front and rear end separation


4. Use vue? What are the commonly used instructions?

use vue
v-if instructions:Is a conditional rendering instruction that deletes and inserts elements according to the true or false of the expression
Syntax: v-if="expression"
v-show Instruction: display content (same as) angular Medium ng-show)
v-else Directive: must and v-if Combined use  Cannot be used alone  Otherwise, an error is reported   Template compilation error
v-for Instruction: v-for The instruction renders a list based on an array, which and JavaScript The traversal syntax of is similar
Syntax: v-for="item in items"
v-bind Instruction: v-bind An instruction can take a parameter after its name separated by a colon. This parameter is usually HTML Properties of elements( attribute)
Syntax: v-bind:argument="expression"
v-model: v-model(The form element will be ignored after it is set value,checked,selected),Commonly used in forms <input> and <textarea>,Let form elements and data realize two-way binding (mapping relationship)
v-on Instruction: v-on Command is used to give the listener DOM Event, which uses syntax and v-bind Is similar, such as listening<a>Click event of element:<a v-on:click="doSomething">
v-text Instruction: v-text The main instruction is to prevent the page from loading for the first time {{}} Appears on the page. Displays the value of the data variable in the object on the bound label content.
Syntax: v-text="expresstion"


5. Are JS and jq familiar

Familiar, the differences between the two are as follows: 1. Essential differences
jQuery It's a JavaScript Function library. jQuery Is based on JavaScript A framework written in language,In essence, it's still JavaScript nothing more.
2,Differences in code writing
jQuery Greatly simplified JavaScript Programming, jQuery Code is heavier than JavaScript Much lighter, jquery The original intention of the design is to use less code and beautifully complete more functions.
3,Differences in use methods
(1)use JavaScript and jQuery Load separately DOM: 
JavaScript It will only be executed once, and jQuery Multiple times.
(2)use JavaScript and jQuery obtain class method:
JavaScript There is no default fetch class Method, and JQuery, Can pass $('.className') call class Methods.


6. Spring MVC workflow

Working principle: 1  The user sends a request to the front-end controller DispatcherServlet. 
2,  DispatcherServlet Request call received HandlerMapping Mapper.
3,  The mapper finds the specific processor(Can be based on xml Configuration and annotation for searching),The generated object and interceptor are returned to the DispatcherServlet. 
4,  DispatcherServlet call HandlerAdapter Adapter.
5,  HandlerAdapter After adaptation, call the specific processor Controller(Back-end Control ). 
6,  Controller Execution completion return ModelAndView. 
7,  HandlerAdapter take controller results of enforcement ModelAndView Return to DispatcherServlet. 
8,  DispatcherServlet take ModelAndView Pass to ViewReslover View parser.
9,  ViewReslover Return specific information after parsing View. 
10,DispatcherServlet according to View Render the view (that is, fill the view with model data).
11, DispatcherServlet Respond to users.


7. The difference between ArrayList and LinkedList

generality: ArrayList And LinkedList All List Interface, so they are all implemented List All the unimplemented methods of are implemented in different ways.
difference: List The implementation of the interface is different
ArrayList Realized List Interface is implemented in the form of array. Therefore, for the demand of fast random acquisition of objects, use ArrayList The implementation efficiency will be better.
LinkedList It is realized by linked list List Interface, so in progress insert and remove It's more efficient than ArrayList High. Suitable for implementation Stack(stack)And Queue(queue). 


8. Data types supported by redis

Redis Five data types are supported: string(String), hash(Hash), list(List), set(Assembly) and zset(sorted set: Ordered set). 


9. Thread problem

Concept: a program can have multiple execution clues executed at the same time. A thread is an execution clue in the program,
         The basic unit of independent operation.
New status: Execute new()method
Ready status: Execution start()method
Running status: Execution run()Method, get CPU resources
Blocking status: Execution sleep(),Give up CPU resources
Death status: available stop()and destroy()Compulsory termination
Implementation method: Inheritance Thread Class, implementation Runnable Interface, implementation Callable Interface
  join(): Thread queue jumping 
sleep()and wait()difference:
sleep()yes Thread Class, give up cpu,cpu To execute other threads, it will recover automatically.
wait()yes Object Class to give the synchronization lock to the thread waiting for the lock, which will not be restored automatically.
run()and start()difference:
run()Is the execution code associated with the thread (a thread must manage the specific execution code).
start()Is to start a thread and make the thread ready.
Optimal number of threads=((Thread waiting time+thread  CPU (time)/thread  CPU (time)*CPU number
(The higher the proportion of thread waiting time, the more threads are required, CPU (the higher the time ratio, the fewer threads are required)


10. Route of Vue

Front end routing and back-end Routing:
Back end Routing: for ordinary websites, all hyperlinks are url Address, all url All correspond to the corresponding resources on the server
Front end Routing: for single page applications, it is mainly through url of hash(#)To switch between different pages. At the same time, hash has another feature. HTTP requests will not contain hash related content, so page Jump in single page programs is mainly realized by hash
In a single page application, this is done by hash The way to change the page is called front-end routing, which is different from back-end routing


11. Why elk+kafka

Because of simple use elk Log collection for io Read, easy to lose data, logstash Too many, bad expansion. Non real time.


12. What tables does MYCAT have

1. Sub database table
Indicates that the data of the table is stored in multiple actual databases, and it is decided to store a piece of data in the table of a database according to certain rules;
When adding data, decide which actual database table to add according to the sub database rules;
When updating and deleting data, first locate the actual database table in which the data is located, and then modify it;
When querying data, query qualified records from each mapped database, and then aggregate and return results;
There are sub database rules, such as rule="auto-sharding-long"
2. Global table
A copy of the table is stored in each database;
When adding, modifying and deleting data, add it in each actual database table. After the operation is completed, the content of each database table is still the same;
When querying the database table, randomly select the data in an actual database table to return;
use type="global"To identify.
3. One to one mapping table
One mycat The logical table in is mapped to an actual database table, and the logical table and the physical table are 1-to-1 mapped;


13. How is rabbitmq implemented

RabbitMQ Use and principle analysis
RabbitMQ It's a realization AMQP(Advanced Message Queuing Protocol)The Message Queuing service of advanced message queuing protocol uses Erlang Language.
Several concept descriptions:
Broker:It provides a transmission service,Its role is to maintain a route from producers to consumers and ensure that data can be transmitted in a specified way,
Exchange: Message switch,It specifies what rules messages follow,Which queue to route to.
Queue:Message carrier,Each message is dropped to one or more queues.
Binding:Binding, its function is to exchange and queue Bind according to routing rules.
Routing Key:Routing keyword,exchange Message delivery is carried out according to this keyword.
vhost:Virtual host,One broker There can be more than one in the vhost,Used as a separation of permissions for different users.
Producer:Message producer,Is the program for delivering messages.
Consumer:Message consumer,Is the program that receives messages.
Channel:Message channel,In each connection of the client,Multiple can be established channel.


Yi Jiu:
Introduce the project
Talk about the business logic of a module
Introduce the middle office architecture
What is Es

Baike Technology:

Class cannot be inherited


Modify a variable. The variable becomes a constant and can only be assigned once. It is generally shared with public static


Modifier method, method cannot be overridden


Final modifies the object, which can no longer point to other references. In other words, the object can no longer accept the assignment of new object


1. Interface and abstraction

(1)Interface features:
 Keywords of interface: interface
a.All the methods are used public abstract Decorated.(Default if you don't write)
b.Interface cannot be instantiated
c.The implementation class must implement all methods of the interface
d.Implementation classes can implement multiple interfaces( java Medium"Multiple inheritance"(relationship)
e.All variables are used public static final Embellished(static const ). 
 (2)What protocol is used for the interface
a.HTTP  Hyper Text Transfer Protocol
b.HTTPS  Secure Hypertext Transfer Protocol
c.FTP  File transfer protocol( Xshell File drag)
d.TCP Network control protocol
e.IP  Internet Protocol
f.UDP  User data protocol
(3) java Features of abstract classes in:
a.Abstract classes can define constructors
b.Abstract classes can declare and use fields
c.If there are abstract methods in a class, the class must be abstract
d.Abstract classes can have ordinary properties, methods, static properties and static methods
e.Abstract methods do not necessarily exist in abstract classes
f.Abstract methods in abstract classes need to be implemented by subclasses. If subclasses do not implement, subclasses also need to be defined as abstract
(4) difference:
a.Abstract classes can declare and use fields; Interfaces cannot, but static interfaces can be created final constant
b.Abstract classes can define constructors, but interfaces cannot
c.Methods in abstract classes can be public,protected,private Or default package;Interface methods are public((interfaces are public whether declared or not) The variables declared in the interface are all by default final , abstract classes can contain non final variable
e.Abstract classes can implement interfaces without providing interface method implementation
f.Interfaces are absolutely abstract and cannot be instantiated. An abstract class cannot be instantiated, but if it contains main Method can be called


2. Can string be inherited? Why

Cannot be inherited because String Class has final Modifier, and final Decorated classes cannot be inherited.

3. Flow

1.Distinguish by flow direction: output flow: OutputStream,Writer Base class
           Input stream: InputSteam,Reader   Base class 2.Data unit: byte stream: byte input stream InputStream,Byte output stream OutputStream
           Character stream: character input stream Reader,Character output stream Writer


4. Difference between throws and throw

throws: It is used to declare all exceptions that may be generated by a method. Instead of doing any processing, it uploads the exceptions to whoever calls me.
  Used after the method declaration, followed by the exception class name
  It can be separated from multiple exception class names by commas
  Indicates that an exception is thrown and handled by the caller of the method
  throws Indicates a possibility of exceptions that do not necessarily occur throw: Is used to throw a specific exception type.
  Used in the method body, followed by the exception object name
  Only one exception object name can be thrown
  Indicates that an exception is thrown and handled by the statement in the method body
  throw An exception is thrown and executed throw Must have thrown some kind of exception  

5. Realization of transaction

(1)Programming transaction management based on POJO Is the only choice for the application. We need to call in code. beginTransaction(),commit(),rollback()And other transaction management related methods, which is programmed transaction management.
(2)be based on TransactionProxyFactoryBean Declarative transaction management
(3)be based on @Transactional Declarative transaction management
(4)be based on Aspectj AOP Configure transactions


6.Mybatis delay principle

use CGLIB Create the proxy object of the target object. When calling the target method, enter the interceptor method,

For example, call a.getB().getName(),Interceptor invoke()Method discovery a.getB()yes null Value,

The saved query Association will be sent separately B Object sql,hold B Query up, then call a.setB(b),

therefore a Object of b The property has a value, and then complete a.getB().getName()Method. This is the basic principle of delayed loading.


7. Database optimization. After answering, he will ask him how to solve the problem of null judgment of fields in where

Database optimization:
1,Indexing in tables is preferred where,group by Used fields.
2,Try to avoid using select *,Returning useless fields will reduce the efficiency of query. As follows:
Optimization method: use specific fields instead*,Only the fields used are returned.
3,Try to avoid using in and not in,It will cause the database engine to abandon the index for full table scanning. As follows:
SELECT * FROM t1 WHERE username IN (SELECT username FROM t2)
Optimization method: if it is a continuous value, it can be used between Replace. As follows:
If it is a subquery, you can use exists Replace. As follows:
SELECT * FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t1.username = t2.username)
4,Try to avoid using or,It will cause the database engine to abandon the index for full table scanning. As follows:
SELECT * FROM t WHERE id = 1 OR id = 3
Optimization method: available union replace or. As follows:
(PS: If or The fields on both sides are the same, as in the example. It seems that the efficiency of the two methods is almost the same, even if union The index is scanned, or (full table is scanned)
5,Try to avoid fuzzy queries at the beginning of the field, which will cause the database engine to give up the index for full table scanning. As follows:
SELECT * FROM t WHERE username LIKE '%li%'
Optimization method: try to use fuzzy query after the field. As follows:
SELECT * FROM t WHERE username LIKE 'li%'
6,Try to avoid null The judgment of value will cause the database engine to abandon the index for full table scanning. As follows:------------------where Field in null Judge how to solve it?
Optimization method: you can add a default value of 0 to the field and judge the value of 0. As follows:
SELECT * FROM t WHERE score = 0
7,Try to avoid where Expression and function operations on the left side of the equal sign in the condition will cause the database engine to abandon the index for full table scanning. As follows:
SELECT * FROM t2 WHERE score/10 = 9
SELECT * FROM t2 WHERE SUBSTR(username,1,2) = 'li'
Optimization method: you can move expressions and function operations to the right of the equal sign. As follows:
SELECT * FROM t2 WHERE score = 10*9
SELECT * FROM t2 WHERE username LIKE 'li%'
8,Avoid using when there is a large amount of data where 1=1 Conditions. Usually, in order to facilitate the assembly of query conditions, we will use this condition by default, and the database engine will give up the index for full table scanning. As follows:
Optimization method: assemble with code sql Make a judgment when, No where plus where,have where plus and. 

8.Dubbo function

9. How to deploy Dubbo? How many ways



1, use web Container( Tomcat,Jetty (etc.) start dubbo Services:
Increase the complexity of port management, tomcat/jetty And so on, dubbo Services also need ports; Waste resources (memory), start separately tomcat,jetty Large memory consumption
Application: need to provide web Service module, general dubbo client You can deploy in this way
2,Use self built Main Method class run spring Container start dubbo Services: Dobbo The elegant shutdown advanced features provided are useless, and there may be defects in writing your own startup class
In the development phase dubbo server You can use this method
3,use Dubbo Provided by the framework Main Method class run Spring Container startup service: officially recommended, dubbo The framework itself provides startup classes(,Elegant shutdown can be realized, which can be used when packaging maven Make it ordinary jar Just a bag.
Application: in production dubbo server It can be deployed in this way.
Copyright notice: This article is CSDN Blogger「HsiunKao」Original articles, follow CC 4.0 BY-SA Please attach the original copy of this Agreement and the link.
Original link:


10. The data types supported by redis, under what circumstances
11. How to realize the persistence of IDS
12. The difference between parallelism and concurrency
13. What is deadlock
14. How to prevent deadlock
15. Implementation principle of synchronous keyword
16. Annotations of springboot, and the annotations and functions contained therein
17. Difference between sleep and wait
18. #{} and ${} differences
20. Design a shiro process by yourself

Some written questions:
1. There are n integers, so that the numbers in front of them move backward by m positions, and the last m numbers become the first m numbers


import java.util.Scanner;public class lianxi36 {public static void main(String[] args) {
   int N =10;
   int[] a = new int[N];
   Scanner s = new Scanner(;
   System.out.println("Please enter 10 integers:");
   for(int i=0; i<N; i++) {
    a[i] = s.nextInt();
   System.out.print("The array you entered is:");
   for(int i=0; i<N; i++) {
     System.out.print(a[i] + " ");
   System.out.print("\n Please enter the number of digits to move backward:");
   int m = s.nextInt();
   int[] b = new int[m];
   for(int i=0; i<m; i++) {
    b[i] = a[N-m+i];
   for(int i=N-1; i>=m; i--) {
   a[i] = a[i-m];
   for(int i=0; i<m; i++) {
    a[i] = b[i];
System.out.print("The array after displacement is:");
   for(int i=0; i<N; i++) {
    System.out.print(a[i] + " ");




2. Given an integer N, print 2*N lines according to the following mode. If N=4, then
Input: n - > integer representing the number of rows
Output: print out the mode according to the specified number of lines

public class printmatrix {
    public static int helper[] = new int[100];
    public static void calc(int n){
        helper[n] = helper[n-1]+n;
    public static void printNum(int n){
        String[] strs = new String[n+1];
        int row = 1;
            String str = new String();
            for(int i=helper[row-1]+1;i<=helper[row];i++){
                str += i;
            strs[row] = str;
        for(String str : strs){
        for(int i=n;i>0;i--){
    public static void main(String[] args) {
        // TODO Auto-generated method stub

3. Talk about your views on webService

WebService,As the name suggests, it is based on Web Services. It uses Web(HTTP)Method to receive and respond to a request from an external system. So as to realize remote call


4. Talk about your views on stored procedures

I understand that stored procedures are predefined SQL Statement, and then store it. When you use it, you can match what you need SQL Statement use Execute(Namely exec)Just call!

5. Known Sales


1> Write the SQL statement to find the data of Amout of each Company with a total of more than 10000.
2> Filter out duplicate data of Company and Amout. Keep only one. Take the above data as an example. The execution result should be:


6. Is there any error in the following code? What's wrong? Please explain the situation.
List list=null;

null No, .size()
You can List<object> aa= new List<object>(); (C#Language, java similar)
It means new One list Object like this.size()You can use it

7. Talk about your views on java Collection classes. Do List, Set and Map inherit from the Collection interface?

Collection Is the most basic collection interface, which declares that it is applicable to JAVA Set (including only) Set and List)General method of. 

Set and List All inherited Conllection;Set With Collection Exactly the same interface, so there is no additional function, unlike the previous two different interfaces List. 

actually Set namely Collection,It's just different behavior.(This is a typical application of inheritance and polymorphism: showing different behaviors.)Set Do not save duplicate elements(As for how to judge the same elements, it is more responsible) 
Map Not inherited from Collection Interface from Map When retrieving elements from a collection, the corresponding value object will be returned as long as the key object is given. 


8. What is the difference between abstract class and interface?

1. Abstract classes can have constructors, and interfaces cannot have constructors 2. There can be ordinary member variables in the abstract class, but there are no ordinary member variables in the interface 3. Abstract classes can contain non Abstract ordinary methods. All methods in the interface must be abstract and cannot have non Abstract ordinary methods 4. The access type of an abstract method in an abstract class can be public,protected And default type although( eclipse No error is reported, but neither should it), but the abstract methods in the interface can only be public Type, and the default is public abstract Type 5. Abstract classes can contain static methods, but interfaces cannot contain static methods 6. Abstract classes and interfaces can contain static member variables. The access type of static member variables in abstract classes can be arbitrary, but the variables defined in interfaces can only be public static final Type, and the default is public static final Type 7. A class can implement multiple interfaces, but can only inherit one abstract class

9. Start a thread using run() or start()?

It must be used to start the thread start()method. When used start()After starting a thread, the thread enters the ready state to make the virtual processor represented by the thread in the running state,

This means that it can be JVM Schedule and execute. This does not mean that the thread will run immediately. When cpu The execution starts only when the time is allocated to it run()method(If any). 

start()Is the method,It calls run()method.and run()The method is what you have to rewrite. run()Method contains the body of the thread. 

10. What are the application servers?

All documents can be classified as static according to the time when the document content is determined Web Document, dynamic web Documents and active documents. frequently-used Web Application servers include: nginx,Apache,Tomcat,WebLogic,Resin,Glassfish,JBoss,WebSphere wait.

11. How to understand the concept of transaction transaction?

Business( transaction)Concept and characteristics of
    A transaction is a series of operations that form a logical unit of work. This logic works
    The operations in the unit as a whole are either all successful or all failed.
    Characteristics of transactions( ACID): 
    1.Atomicity( Atomicity): 
      A series of operations in a transaction are regarded as an atomic logical unit of work, which works
      All operations in the unit either succeed or fail.
    2.Consistency( Consistency): 
      The data state of the database system before and after the transaction operation is from a consistency state
      Transition to another consistency state.
      When multiple transactions are executed concurrently, they cannot see each other's operation process.
    4.Persistence( Durability)
      Once the transaction is executed successfully, the impact on the database system is persistent.

12. Is String the most basic data type? What is the difference between String and StringBuffer?

String Not a basic data type
(1)String:Is the object not the original type.Is immutable,Once created,You can't change its value.For existing String Object modification is to recreate a new object,Then save the new value.String yes final class,That is, it cannot be inherited
(2)StringBuffer:Is a mutable object,When you modify it, it won't be like String Then recreate the object. It can only be built through the constructor. After the object is built,Memory space is allocated in memory,And initially save one null.

   towards StringBuffer You can use it when you pay the value append method.

13. What's the difference between int and Integer?

1,Integer yes int Packaging class, int then is java A basic data type of 2 Integer Variables must be instantiated before they can be used, and int Variables do not need 3 Integer Is actually a reference to an object, when new One Integer In fact, a pointer is generated to point to this object; and int Directly store data value 4 Integer The default value for is null,int The default value for is 0

14. What are the similarities and differences between runtime exceptions and general exceptions?

An exception indicates an abnormal state that may occur during the operation of the program,

Runtime exception: it refers to the exception that may be encountered in the normal operation of the virtual machine. It is a common running error. java The compiler requires that methods must declare that they throw possible non runtime exceptions,

However, it is not required to declare that an uncapped runtime exception is thrown.
General exceptions: java The compiler forces us to correct the exceptions that occur try...catch...Otherwise, the program cannot be compiled

15. Tell the life cycle of Servlet and the difference between Servlet and CGI?

Servlet The life cycle of is divided into five stages:
Instantiation: Servlet Container creation Servlet Class.
Initialization: called by this container init()Method, usually apply for resources.
Service: called by container service()Method, (i.e doGet()and doPost()). 
Destruction: in release Servlet Call before instance destroy()Method, which usually releases resources.
Not available: instance that frees up memory.
CGI(Common Gateway Interface General Gateway Interface) program to realize data in Web Transmission on, using Perl Written in such a language, for each request made by the client,

Must create CGI A new instance of the program, which takes up a lot of memory resources. That's why it was introduced Servlet Technology.
Servlet It's a java The application program is written to run on the server, process the request information and send it to the client. For client requests, you only need to create Servlet Instance once, so a lot of memory resources are saved.

Servlet It remains in memory after initialization, so it doesn't need to be loaded every time a request is made.

16. State the storage performance and characteristics of ArrayList, Vector and LinkedList

ArrayList and Vector Data is stored in an array. The number of elements in this array is greater than the actual stored data, so as to add and insert elements. They all allow elements to be indexed directly by serial number,

However, inserting elements involves memory operations such as array element movement, so index data is fast and inserting data is slow, Vector Due to the use of synchronized Method (thread safety), usually with low performance ArrayList Poor, and LinkedList Using a two-way linked list for storage,

Indexing data by serial number requires forward or backward traversal, but only the front and rear items of this item need to be recorded when inserting data, so the insertion speed is fast.
one.Synchronization:Vector It is thread safe, that is, synchronous, and ArrayList The online program is unsafe, not synchronous
two.Data growth:When growth is needed,Vector The default growth is the original one, and ArrayList But it's half the original

17. Conditions:
Student form: student number sno, name
Course transcript student_score: student number sno, subject stype, score
(1) Query the student number, student name, total number of courses selected and the total score of all courses of all students
(2) Retrieve the student information in descending order of "01" course score less than 60
(3) Query the information of at least one course that is the same as that of the student with student number "01"
Write the rest interface for adding student information, including the notes used
(4).xml,sql layer


Inster written test:
1. Difference between process and thread

process:It is the basic unit for the system to allocate and manage resources
thread :An execution unit of a process, It is the entity of in-process scheduling CPU Basic unit of dispatch and dispatch, It is the basic unit of independent operation smaller than the process. Threads are also called lightweight processes, Thread is the smallest unit of program execution.
 A program has at least one process, A process has at least one thread.
 The process has its own independent address space, Every time you start a process, The system will allocate address space for it, Creating a data table to maintain code segments, stack segments, and data segments is very expensive.
Threads share data in the process, Use the same address space, therefore CPU The cost of switching a thread is much less than that of a process, At the same time, the cost of creating a thread is much smaller than that of a process.
 Communication between threads is more convenient, Threads in the same process share data such as global variables and static variables, The communication between processes needs to be carried out in the way of communication.
 How to deal with synchronization and mutual exclusion is the difficulty of writing multithreaded programs.
 Multi process programs are more robust, The process has a separate address space, After a process crashes, In protected mode, it will not affect other processes,
Threads are just different execution paths in a process. Threads have their own stacks and local variables, But there is no independent space between threads, So there may be a problem with one thread, Which leads to problems in the whole procedure


2. What is the impact of multithreading concurrency on the life cycle of threads
3. Characteristics of queue and stack. In what actual cases?
4. The function of synchronized. What other locks are commonly used in java?
5. What is the difference between synchronized and volatile?
6. Scope and life cycle of spring Bean
7. Six common annotations and functions of spring
8. Explain what is a transaction and what problems will be caused by multithreaded transaction concurrency, and briefly describe the four isolation of transactions
9. What is aop? Several notification methods of spring
10. Draw the memory operation diagram of jvm and explain its function
11. Handwriting quick sorting algorithm
12. Handwriting thread safe singleton mode
13. Design a structure diagram of second kill




Huawei headquarters interview:
It's mainly something at the bottom. The general topic of the two Huawei project teams today is.
① Basic data types and their packaging classes (mainly basic data types, why packaging classes, and what are the differences between basic data types and packaging classes as formal parameters)
② jvm's memory model [what are the common parts of threads that are private to threads, what are stored respectively, what is changed to the java8 method area (changed to the metadata area, and ask what is the difference between them), what is also called Java memory leakage (how to avoid memory leakage -- mainly the reference type of objects)], Garbage collection mechanism (the division between the new generation and the old generation, what recycling algorithms they use respectively, what are the common garbage collectors, what are their characteristics, and whether their garbage collectors are the same when running in client and server mode (what is called client, server mode, jit)). The second is very important. Both project teams asked
③ What is the difference between the underlying implementation of hashmap in 1.7 and 1.8, and what are the advantages of these improvements (as well as the extended bucket sorting (the fastest sorting, sacrificing memory and ensuring performance), the overall structure of red black tree and its four rules). The two project groups asked, and the second asked deeper.
④ How does spring ensure thread safety when creating objects through bean s
⑤ Because I wrote the difference between websocket, http and https in my project (mainly the encryption of the latter, what is the basis of his encryption), how to ensure that the information will not be forged, tampered with or intercepted when communicating between two people (mainly symmetric encryption and non symmetric encryption in reversible encryption, as well as their cooperation), There is also the certificate problem in the trust chain.
⑥ The difference between abstract classes and interfaces
⑦ What thread safe classes have you used? Why are they thread safe? If you are given a thread unsafe class, how can you change it to thread safe.
⑧ Build a rough vue
⑨ How to execute a method in a jar. (there is mainly a MANIFEST.MF file, where main class. Is configured, and then via java -jar abc.jar)
⑩ Recently, cpu and memory utilization of a server has suddenly increased. How to check it.
① Tell me about the specific implementation of single sign on
② I said I studied c and Java in college. He asked me that java8 has a new feature called lambda. What is its similarity with c language.

Green and:
1. How many years of working experience?
2. What framework is used?
3. Is the front and rear ends separated
4. Use vue? What are the commonly used instructions?
5. Are JS and jq familiar
6. Spring MVC workflow
7. The difference between ArrayList and LinkedList
8. Data types supported by redis
9. Thread problem
10. Introduce the project
11. Route of Vue
12. Why elk+kafka
13. What tables does MYCAT have
14. How is rabbitmq implemented

Yi Jiu:
Introduce the project
Talk about the business logic of a module
Introduce the middle office architecture
What is Es

Baike Technology:
1. Interface and abstraction
2. Can string be inherited? Why
3. Flow
4. Difference between exception and throw
5. Realization of transaction
6.Mybatis delay principle
7. Database optimization. After answering, he will ask him how to solve the problem of null judgment of fields in where
8.Dubbo function
9. How to deploy Dubbo? How many ways
10. The data types supported by redis, under what circumstances
11. How to realize the persistence of IDS
12. The difference between parallelism and concurrency
13. What is deadlock
14. How to prevent deadlock
15. Implementation principle of synchronous keyword
16. Annotations of springboot, and the annotations and functions contained therein
17. Difference between sleep and wait
18. #{} and ${} differences
20. Design a shiro process by yourself

Some written questions:
1. There are n integers, so that the numbers in front of them move backward by m positions, and the last m numbers become the first m numbers
2. Given an integer N, print 2*N lines according to the following mode. If N=4, then
Input: n - > integer representing the number of rows
Output: print out the mode according to the specified number of lines
3. Talk about your views on webService
4. Talk about your views on stored procedures
5. Known Sales


1> Write the SQL statement to find the data of Amout of each Company with a total of more than 10000.
2> Filter out duplicate data of Company and Amout. Keep only one. Take the above data as an example. The execution result should be:


6. Is there any error in the following code? What's wrong? Please explain the situation.
List list=null;
7. Talk about your views on java Collection classes. Do List, Set and Map inherit from the Collection interface?
8. What is the difference between abstract class and interface?
9. Start a thread using run() or start()?
10. What are the application servers?
11. How to understand the concept of transaction transaction?
12. Is String the most basic data type? What is the difference between String and StringBuffer?
13. What's the difference between int and Integer?
14. What are the similarities and differences between runtime exceptions and general exceptions?
15. Tell the life cycle of Servlet and the difference between Servlet and CGI?
16. State the storage performance and characteristics of ArrayList, Vector and LinkedList
17. Conditions:
Student form: student number sno, name
Course transcript student_score: student number sno, subject stype, score
(1) Query the student number, student name, total number of courses selected and the total score of all courses of all students
(2) Retrieve the student information in descending order of "01" course score less than 60
(3) Query the information of at least one course that is the same as that of the student with student number "01"
Write the rest interface for adding student information, including the notes used
(4).xml,sql layer



Softcom power telephone interview:

1. Differences between JDBC and hibernate


(1)hibernate and jdbc The main difference is, hibernate First retrieve the mapping object in the cache( Namely hibernate It's an object),and jdbc Directly operate the database.
(2)Hibernate yes JDBC Lightweight object encapsulation, which is an independent object persistence layer framework, and App Server,and EJB There is no necessary connection. Hibernate Can be used in any JDBC Where it can be used
(3)Hibernate It's a and JDBC Closely related framework, so Hibernate Compatibility and JDBC The driver has a certain relationship with the database, but it is different from those who use it Java Procedures, and App Server It doesn't matter, and there is no compatibility problem.
One more thing,Correct use JDBC technology,It must be more efficient than hibernate Better,because hibernate Is based on jdbc Technology of.



2. Implementation principle of echarts


Pixel based
single html,Similar to painting with a brush on a canvas
Echarts be based on canvas Draw a picture
Object based model
Multiple graphic elements
high fidelity



3. How does Ajax interact with the front and back console


1,url Request address 2 type Request method: the default is'GET',Commonly used are'POST'3,dataType Common data format'json'Can also be formatted as'html'4,data Set the data sent to the server 5 success Set the callback function after the request is successful error Set the callback function after the request fails async Set whether to be asynchronous. The default value is'true',Represents asynchrony



Shanghai CITIC Information Development Co., Ltd.:

1. What is the relationship between SSMS and their respective roles


1.Persistence layer: DAO Layers( mapper Layer) (of mybatis Module)
DAO Layer: mainly responsible for the interaction design with the database to deal with the persistence of data.
DAO The design of the first layer is the design DAO Interface, that is, what you see in the project Dao Bag.
Then in Spring of xml The implementation class that defines the interface in the configuration file can call the interface in other modules for data service processing, instead of caring about the specific implementation class of the interface. What is often used here is the reflection mechanism. DAO Layered The data source configuration and parameters related to database connection are in the Spring Configuration in the configuration file.
ps:(In some projects Dao Layer, written as mapper,Take it as a meaning.) two.Business layer: Service Layer of spring Module)
Service Layer: mainly responsible for the logical application design of business module. That's what you see in the project Service Bag.
Service The design of layer is to design the interface first, and then design the class it implements. That's what you see in the project service+impl Bag.
Then in Spring of xml Configure the association of its implementation in the configuration file. In this way, we can call in the application. Service Interface for business processing.
Finally, by calling DAO Layer defined interface to implement Service Specific implementation classes.
ps:(Service The business implementation of layer needs to be called to the defined DAO Layer interface.)
3.Control layer/Presentation layer: Controller Layers( Handler Layer) (of springMVC Module)
Controller Layer: mainly responsible for the process control of specific business modules, that is, what you see controller Bag.
Controller Layer to call Service Layer interface to control business processes, and the configuration of control is also in Spring of xml In the configuration file, there will be different controllers for specific business processes.
4.View Layer of springMVC Module)
Responsible for the front desk jsp For the display of the page, this layer needs to be connected with Controller Layer development.
Jsp Send request, controller Receive request, process, return, jsp Echo data.



2. What are the drivers for using Oracle

oracle The driver of the database is fixed. When connecting, write directly oracle.jdbc.driver.OracleDriver that will do

3. What are the implementation technologies of MVC mode


MVC The full name is Model View Controller,It's a model(model)-view(view)-controller(controller)An abbreviation of, a software design model, organizes code by separating business logic, data and interface display, and gathers business logic into one component. It does not need to rewrite business logic while improving and customizing interface and user interaction. MVC It is uniquely developed to map the traditional input, processing and output functions in the structure of a logical graphical user interface.
MVC It is a kind of use MVC(Model View Controller Model-view-(controller) design creation Web Application mode:
Model(Model) represents the core of the application (such as database record list).
View(View) displays data (database records).
Controller(The controller processes the input (writes the database record).
MVC Mode also provides access to HTML,CSS and JavaScript Complete control of.
Model(Model) is the part of an application that handles the application data logic.
  Usually, model objects are responsible for accessing data in the database.
View(View) is the part of the application that handles the display of data.
  Typically, views are created from model data.
Controller(Controller) is the part of an application that handles user interaction.
  Usually, the controller is responsible for reading data from the view, controlling user input, and sending data to the model.
MVC Layering helps manage complex applications because you can focus on one aspect at a time. For example, you can focus on view design without relying on business logic. It also makes it easier to test the application.
MVC Layering also simplifies group development. Different developers can develop view, controller logic and business logic at the same time.



4. The difference between get and post


5.redis caching mechanism


Database cache:
sql Statement time key Value, query result resultSet yes value,When the same query statement accesses( select * from t_product),As long as it has been queried, the call cache returns directly resultSet,It saves the time for the database to read disk data.
Persistent layer cache:
Reduce the time of connecting to the database; Reduced resultSet The process of encapsulating into objects.
Cache of business layer and control layer:
Reduce the call hierarchy.
Describe the logic of caching in the business layer:
Query commodity information
Judge whether the current query has data in the cache
  If there is data, return directly and the current request ends;
  If there is no data, query the persistence layer database data, obtain the data storage and cache a copy for subsequent access;
Cache avalanche/Buffer breakdown
Massive request access server,The performance of the server is supported by the cache,Once a certain range of cache data misses,Requested data access to the database;Can't bear the pressure and cause downtime--restart--Massive requests have not disappeared--Downtime --restart,The system is unavailable for a long time;This is the avalanche of caching.

Duofei network technology:

1. Difference between = = and equals()

about==,Compare whether the values are equal. If it acts on a variable of basic data type, directly compare whether the stored "values" are equal; If it acts on a variable of reference type, the address of the object pointed to is compared
about equals Method, note: equals Method cannot act on variables of basic data type,

equals inherit Object Class to compare whether it is the same object. If there is no pair equals Method, the address of the object pointed to by the variable of reference type is compared;

such as String,Date Equal class pair equals If the method is rewritten, the content of the object pointed to is compared.

2. The difference between + + i and i + +

i++Is to assign value first and then increase by itself;++i It is self increment first and then assignment.

3. What object does hibernate use to access the database


Hibernate,about java A very important thing for persistence layer. I can't write a lot of my own configurations.
Environmental Science: jdk1.8,eclipse-jee-oxygen,mysql-connector-java-5.1.46,hibernate 5.2.
First make sure your jdk,eclipse and mysql Put it on. Then download jar Bag, mysql and hibernate of jar Bag.
Then install JBoss plug-in unit, eclipse in Help-----eclipse market Inside input JBoss Search and find JBoss After that, install,Here you only need to correspond hibernate Just the ones.


4. Storage mode of Oracle


1, File system
    (The simplest way)
     Divide a part of space from local storage to provide storage for data.
      ① Format this area (this is windows Your name. stay Linux and Unix In the system, it is called creating a file system.)
      ② Mount the disk( windows Middle name (drive letter)      ## An interface to the access area
           Advantages: data files are easy to access and easy to manage.
           Disadvantages: the access performance is affected, and there is an additional layer of file system in the middle
2, Bare equipment
    The storage space is not formatted, and the data is directly stored in the storage space.
    Ordinary users cannot access it. Only database software can directly access it.
           Advantages: less file system middle tier, faster access, I/O 20% better performance than file system%
           Disadvantages: inconvenient management, unable to cp,rf And so on. But it can be used Oracle Tool handling( dd,RMAN)
III ASM disk
      ASM:Automatic Storage Management(Oracle 10g (later)
      provide OMF management style:
      When creating a database manually: db_create_file_dest=+DISK1
      Log file:   db_create_logfile_dest=+DISK1
      ASM Disk, via asm instance Manage. Database instance direct access asm Instance, so that the access method is more compact and direct
      Oracle 11g Later, the operating system and ASM Interaction between
4, Start management ASM Examples of
      1.edit ASM Initialization parameter file content $ORACLE_HOME/dbs/init+ASM.ora
      2.Enable ASM example
      $ export ORACLE_SID=+ASM
      $ sqlplus / as sysdba
      SQL> startup nomount
      ASM instance started
      Total System Global Area  82736155 bytes
      Fixed Size                         6254372 byyes
      Variable Size                     73625362 bytes
      ASM Cache                        25173827 bytes

 3.(First use ASM)An error will be reported when starting
      ORA-29701 unable to connect to Cluster Manager
      The following treatment is required:
      $ cd $ORACLE_HOME/bin
      $ su root(with root Execute as, but do not change environment variables)
      $ ./localconfig delete
      $ ./localconfig add
      5.Bare device binding relationship
      /dev/raw/raw2: bound to major 58,minor 0
      /dev/raw/raw3: bound to major 58,minor 1
      /dev/raw/raw4: bound to major 58,minor 2
      /dev/raw/raw5: bound to major 58,minor 3
      6.Create disk group
      create diskgroup disk1 normal redundancy
           failgroup fg1 disk '/dev/raw/raw1' name d1
           failgroup fg2 disk '/dev/raw/raw2' name d2
           failgroup fg3 disk '/dev/raw/raw3' name d3
           failgroup fg4 disk '/dev/raw/raw4' name d4
           failgroup fg5 disk '/dev/raw/raw5' name d5
           failgroup fg6 disk '/dev/raw/raw6' name d6;
      Note: external redundancy     (Primary) indicates that redundancy requires only one fault group, assuming this disk pair                                             Apply to running database operations
           normal redundancy      The standard redundancy provides two-way mirroring, which requires two faults in a disk                                             Barrier group
           high redundancy          Providing three-way mirror requires three disk groups in one disk
      create diskgroup disk1 external redundancy disk '/dev/raw/raw3';
      The files in each disk in a disk group are roughly or finely divided into 1 M It is applicable to all data in the disk warehouse, and the unit of division is 128 KB Bit unit distribution file for OLTP. 
      7.View new available disk groups
      SQL> select GROUP_NUMBER,name,type,total_mb,free_mb from v$asm_diskgroup;
      SQL> select group_number,disk_number,name,failgroup,create_date,path from v$asm_disk;

    8.Delete disk group
      drop diskgroup disk1
      drop diskgroup disk1 including contents;((there are database objects in the disk group)
      9.Adding disks to a disk group
      alter diskgroup disk1 ass failgroup fg4 disk '/dev/raw/raw4' name d4;
      10.Remove a disk member from a disk group
      alter diskgroup disk1 drop disk d4;
      11.You can modify the disk group at the same time DROP and ADD Operation, so that only one balancing operation occurs, reducing CPU and I/O time
      aletr diskgroup disk1 add failgroup fg4 disk '/dev/raw/raw4' name d4 group disk d3;



Beijing alangre:

1. How hibernate handles sql statements

hibernate Originally supported the original sql Call execution sql When calling a method, pay attention to the required parameters
@Autowiredprivate SessionFactory sessionFactory;

2. How does JDBC handle the parameters passed in from sql


1, Parameters in array form
  Advantages: simple for sql,It can save some memory space. Reduce the amount of code and make it easy to read.
    1,The same parameters cannot be reused, so array Take up more space. (of course, in terms of current hardware, this is not enough space/Memory, extra time spent adding array values (completely insignificant)
    2,If it is in Parameters to be dynamically spliced(?)Placeholder. (I think the most troublesome and cumbersome, expansion: oracle yes in Maximum support (1000)
    3,If sql There are too many parameters in, which is actually difficult to read and modify.
Personal habit List Add parameters, and then List convert to Array. 
The advantage is: if you use an array, when sql If there are dynamic conditions, the array length cannot be determined. And use List You don't need to maintain it yourself.
II map Formal parameters
    1,Solved in Parameter problem.
    2,Parameter values can be reused.
III javaBean Formal parameters
If the parameter is passed JavaBean Spread dao Layer, then don't put bean convert to map. Relatively, if it is through map Spread dao Layer, also used map The form does not need to be converted into javaBean. 


3. Role of tags and tag merging in SVN

SVN Merge( Merge)"Function: this function is used to branch( branch)And trunk( Trunk)For merging. Through automatic merging, the changes of most files can be merged together to form a set of files with all changes.
SVN yes Subversion Is an open source version control system RCS,CVS,It adopts branch management system, and its design goal is to replace CVS. Many version control services on the Internet have changed from CVS Migrate to Subversion. 

4. Use Vue JS development


So what is Vue What about the components? It is vue.js One of the most powerful functions is extensible html Element, which encapsulates reusable code, is also Vue Instance, you can accept the same option object(In addition to some root level specific options) And provide the same life cycle hook.
Component system is Vue.js One of the important concepts is that it provides an abstraction that allows us to use independent and reusable small components to build large-scale applications. Any type of application interface can be abstracted into a component tree:
So what is a component?
Components can be extended HTML Element, encapsulating reusable HTML We can think of custom components as HTML Element.
What are the benefits of using components?
Improve development efficiency
Easy to reuse
Simplify debugging steps
Improve the maintainability of the whole project
It is convenient for multi person collaborative development



Palm edge information technology:

1.Linux basic operation commands, how to view file contents


Commands for viewing file contents:
cat     Display the content from the first line and output all the content
tac     Display the contents in reverse order from the last line and output all contents
more    According to the window size, the real file content page by page
less    and more Similar, but it has the advantage of turning the page forward and searching for characters
head    Show only the first few lines
tail    Show only the last few lines
nl      be similar to cat -n,Output line number when displaying
tailf   be similar to tail -f And tac (Not commonly used)
cat The function of is to continuously output the contents of the file on the screen from the first line.
cat Syntax: cat [-n]  File name(-n :  (when displayed, output together with line number)
tac The function of is to reverse the file from the last line and output the content data to the screen.
tac Syntax: tac File name.
2.more and less((common)
more Similar function cat ,cat The command is that the contents of the entire file are displayed on the screen from top to bottom. more It will be displayed page by page to facilitate users to read page by page, and the most basic instruction is to press the blank key( space)On the next page, press b The key will go back( back)One page display, and there is the function of searching strings. more The command reads the file from front to back, so the entire file is loaded at startup.
Command format:
more [-dlfpcsu ] [-num ] [+/ pattern] [+ linenum] [file ... ] 
Command function:
more Command and cat The same function is to view the contents of the file, but the difference is more You can view the contents of the file by page, and also support functions such as direct line jump.
Command parameters:+n      From the first n Line start display-n       Define screen size as n that 's ok+/pattern Search for the string before each file is displayed( pattern),Then start the display after the first two lines of the string  -c       Clear the screen from the top and display-d       Hint“ Press space to continue,'q' to quit(Press spacebar to continue, press q Press exit to disable the ringing function-l        ignore Ctrl+l(Page feed) character-p       Page change the file by clearing the window instead of scrolling, and-c Similar options-s       Display consecutive blank lines as one line-u       Remove the underline from the contents of the document
Common operation commands:
Enter    down n Line, need to be defined. The default is 1 line
Ctrl+F   Scroll down one screen
Space bar  Scroll down one screen
Ctrl+B  Return to previous screen=       Output the line number of the current line
: f     Output file name and line number of the current line
V      call vi editor !command   call Shell,And execute the command 
q       sign out more
Usage example:
Example 1: display the contents from line 3 in the file
cat test.log                   #Show all log contents
more +3 test.log               #Display the log content from the third line
Example 2.Set the log content to display 4 lines per screen
more -4 test.log
Example 3.Find the first occurrence from the file"liu"The line of the string and displays the output from the first two lines there
more +/liu test.log
Example 4.When there are too many files in a directory, you can use more To display in pages. It has to be connected with the pipeline | Combine
cat test.log | more -5   #"|" refers to the pipeline, which is used to take the output of the previous command as the input of the following command
less The tool is also a tool for pagination display of files or other output linux It is an orthodox tool for viewing the contents of files, and its function is extremely powerful. less Compared with more More elastic. stay more When, we can't turn forward, we can only look back, but if we use it less Can be used when [pageup] [pagedown] Wait for the function of the key to turn the file forward and backward, which is easier to view the content of a file! In addition, in less It can have more search functions, not only downward search, but also upward search.
Command format:
less [parameter]  file 
Command function:
less And more Similar, but using less You can browse files at will, but more It can only move forward, but not backward, and less The entire file is not loaded until you view it.
Command parameters:-b <Buffer size> Sets the size of the buffer-e  When the file display ends, it will leave automatically-f  Force the opening of special files, such as peripheral codes, directories, and binaries-g  Mark only the last keyword searched-i  Ignore case when searching-m  Display similar more Percentage of commands-N  Displays the line number of each line-o <file name> take less The output content is saved in the specified file-Q  Do not use warning tone-s  Displays a row of consecutive empty lines-S  If the line is too long, the excess will be discarded-x <number> Will“ tab"The key is displayed as a specified number space/String: the ability to drill down on "string"?String: the ability to search up for "string"
n: Repeat previous search (and / or ? (related)
N: Reversely repeats the previous search (and / or ? Relevant)
b  Turn back one page
d  Turn back half a page
h  Display help interface
Q  sign out less command
u  Scroll forward half a page
y  Scroll forward one line
Space bar to scroll one line
Press enter to scroll through the page
[pagedown]:  Turn down a page
[pageup]:    Turn up a page
Usage example:
Example 1: ps View process information and pass less Pagination display and line number display
ps -ef|less -N
Example 2.Browse multiple files
less test2.log test.log
Input: n After, switch to test.log
Input: p After, switch to test2.log
ps: You can also use when you are browsing a file :e Command to open another file.
less file1
:e file2
Additional remarks
  (1)Full screen navigation
ctrl + F - Move one screen forward
ctrl + B - Move back one screen
ctrl + D - Move half screen forward
ctrl + U - Move half screen backward
  (2)Single line navigation
j - Move one line forward
k - Move back one line
  (3)Other navigation
G - Move to last line
g - Move to first row
q / ZZ - sign out less command
  (4)Other useful commands
v - Edit the current file using the configured editor
h - display less Help documentation for
&pattern - Only lines that match the pattern are displayed, not the entire file
  (5)Tag navigation
When used less When viewing a large file, you can mark it at any location, and you can navigate to the text location marked with a specific mark through the command:
ma - use a The current position of the tag text
'a - Navigate to tags a place
more, less All have search function, press/ Then enter the string you want to find and press Enter OK, press n(next) I'll keep looking, in uppercase N It's going back(upper)Find, press q(quit)perhaps ZZ leave
3.head and tail((common)
head and tail It is usually used when only the first or last lines of the file need to be read. head The function of is to display the first few lines of the file
head Syntax: head [n number] file name (number Display rows)
tail The function of is exactly the same as head Instead, only the last few lines are displayed
tail Grammar of:tail [-n number] file name
View the first 1000 lines of the log file
  1. head -n 1000 log file
View the last 1000 lines of the log file
tail -f -n 1000 log file  (Print the latest log information in real time)
tail -1000n log file(Print the latest log information in real time)
tail -1000 Log file (print out the last 1000 pieces of information in the log file)
tail -n +1000 Log file (display log information from line 1000)
See how many lines in the middle of the log file
cat log file |  head -n 3000 | tail -n + (Not commonly used)
nl Functions and cat -n Similarly, output all the contents from the first line and display the line number
nl Syntax: nl file name



2. How are design patterns reflected in the coding process


1,Opening and closing principle: a software entity should be open to expansion and closed to modification. That is, the software entity should try to expand without modifying the original code. a,The basic functions of abstraction remain unchanged and will not be modified; b,Encapsulate the variability. 2. Richter transformation principle: a parent class can be replaced by a child class. The principle of Richter transformation is a supplement to the principle of opening and closing. Violating the principle of Richter transformation is a violation of the principle of opening and closing, and is the basis of the agency model.
Pay attention to the following points when using:
    1,The subclass must implement all the methods of the parent class;
    2,Try to design the parent class as an abstract class or interface;
    3,Dependency Inversion Principle: abstract classes do not depend on details, details should depend on abstractions, and high-level modules should not depend on low-level modules. They all depend on abstractions.

4,Interface isolation principle: use multiple special interfaces instead of a single general interface, that is, the client should not rely on those interfaces it does not need; 5. Dimitri principle: one object should know as little as possible about other objects. The coupling degree of each object is relatively low and can run independently; 6. Aggregation principle: use aggregation classes to achieve code reuse, rather than using inheritance relationships to reuse code; 7. Single principle: a class is responsible for the corresponding responsibilities of only one functional domain.


Nanjing weixiaobao:

1. Functions of JSP built-in objects


1,request object
request Object is javax.servlet.httpServletRequest Object of type. This object represents the request information of the client and is mainly used to accept the request information through HTTP Data transferred to the server by the protocol. (including header information, system information, request mode, request parameters, etc.). request The scope of the object is a request.
2,response object
response It represents the response to the client, mainly JSP The object processed by the container is passed back to the client. response Object also has scope, which is only used in JSP Valid within the page.
3,session object
session Object is an object automatically created by the server and related to user requests. The server generates one for each user session Object, which is used to save the user's information and track the user's operation status. session Object internal use Map Class to save data, so the format of saving data is“ Key/value".  session Object value You can make complex object types, not just string types.
4,application object
 application Object can save information in the server until the server is shut down, otherwise application The information stored in the object will be valid throughout the application. And session Compared to the object, application The object life cycle is longer, similar to the "global variable" of the system.
5,out object out Object used in Web Output information in the browser and manage the output buffer on the application server. in use out When the object outputs data, the data buffer can be operated to remove the residual data in the buffer in time to make room for other outputs. After the data output is completed, the output flow shall be closed in time.
6,pageContext object
pageContext Object is used to obtain parameters in any range, through which you can obtain JSP Page out,request,reponse,session,application And other objects. pageContext The creation and initialization of objects are completed by the container JSP You can use it directly in the page pageContext Object.
7,config object
config The main function of the object is to obtain the configuration information of the server. adopt pageConext Object getServletConfig() Method can get a config Object. Be a Servlet During initialization, the container passes some information through config Object passed to this Servlet.  Developers can web.xml The file is a file in the application environment Servlet Procedures and JSP The page provides initialization parameters.
8,page object
page Object representation JSP Itself, only in JSP Inside the page is legal. page The implicit object essentially contains the current Servlet Variables referenced by the interface, similar to Java In programming this Pointer.
9,exception object
exception Object is used to display exception information only when it contains isErrorPage="true" Can only be used in the general page JSP Using this object in a page will not compile JSP Documents. excepation Object and Java Like all objects in the system, it has the inheritance structure provided by the system. exception Object defines almost all exceptions. stay Java In the program, you can use try/catch Keyword to handle exceptions; If in JSP An exception that is not caught in the page will be generated exception Object and put exception Object transfer to page In the error page set in the instruction, and then deal with the corresponding error in the error page exception Object.



2. Bubble algorithm


 1 public class MyBubbleSort { 2  3     public static void main(String[] args) { 4         int[] arr = {3, 2, 5, 1, 8, 1, 11, 8}; 5         int[] results = bubbleSort(arr); 6         for(int item : results){ 7             System.out.print(item + "   "); 8         } 9     }10 11     /**12      * Bubble sort, ascending order 13 * the smaller values in the array sink upward, and the larger ones float upward! 14      */15     public static int[] bubbleSort(int[] arr) {16         // The outer for loop controls the number of cycles 17) for (int i = 0; I < arr.length; I + +) {18) int tem = 0;19 / / the inner for loop controls the two adjacent elements for comparison 20) for (int j = I + 1; J < arr.length; J + +) {21) if (arr [i] > arr [J]) {22                    tem = arr[j];23                    arr[j]= arr[i];24                    arr[i] = tem;25                }26             }27         }28         return arr;29     }30 }


Nanjing real point real distribution network technology:

1.JAVA serialization


----What is serialization?--1--java Serialization refers to java The process of converting an object into a sequence of bytes, and java Deserialization refers to restoring a sequence of bytes to java Object process--2--Serialization: the main use of object serialization is to ensure the integrity and transitivity of objects when passing and saving objects. Serialization is to convert an object into an ordered byte stream for transmission on the network or saving in a local file. Stored in serialized byte stream java The state of the object and related description information. The core function of serialization mechanism is the preservation and reconstruction of object state.--3--Deserialization: after the client obtains the serialized object byte stream from the file or the network, the object is reconstructed through deserialization according to the object state and description information saved in the byte stream.--4--Serialization is to write the entity object state into the ordered byte stream according to a certain format. Deserialization is to reconstruct the object from the ordered byte stream and restore the object state
----Why do I need serialization and deserialization
When two processes communicate remotely, they can send various types of data to each other, including text, pictures, audio, video, etc., and these data will be transmitted in binary form on the network.
When two java When communicating, the object should be transferred. How to transfer the object, through serialization and deserialization.
In other words, the sender needs to convert the object into a byte sequence and then transmit it on the network. On the other hand, the receiver needs to recover from the byte sequence java object
----Benefits of serialization--1--Permanently save the object, save the byte sequence of the object to the local file or database, and realize the persistence of the data. Through serialization, the data can be permanently saved to the hard disk,--2--Using serialization to realize remote communication, the byte sequence of the object can be transmitted on the network.--3--Passing objects between processes
----Serialization algorithm steps--1--Export the class metadata related to the object instance--2--Recursively output the superclass description of the class until there are no more superclasses--3--After the class metadata is finished, start to output the actual data value of the object instance from the superclass that you know best.--4--Recursively output the data of the instance from top to bottom
----Java How to implement serialization and deserialization--1-- JDK Serialization in class library API Represents the output object stream
its writeObject(Object obj)Method can be specified on the parameter obj Object is serialized, and the resulting byte sequence is written to a target output stream; the object input stream
its readObject()Method reads byte sequences from the source input stream, deserializes them into an object, and returns them
--2--Requirements for serialization
Only realized Serializable or Externalizable The object of the interface can be serialized, otherwise an exception will be thrown!
--3--realization java Methods of object serialization and deserialization
example a Class whose objects need to be serialized. There are three methods
If class a Only achieved Serializable Interface, then
ObjectOutputStream The default serialization method is adopted a Object's non transient Serialize instance variables
ObjectInputStream The default deserialization method is adopted a Object's non transient Deserialize instance variables
If class a Only achieved Serializable Interface, and also defines a Object writeObject(ObjectOutputStream out) and readObject(ObjectInputStream in),be
ObjectOutputStream call a Object writeObject(ObjectOutputStream out)Serialize the method of
ObjectInputStream call a Object readObject(ObjectInputStream in)Serialize the method of
If a Class implements ExternaInalizable Interface, and User Class must implement readExternam(ObjectInput in)and wiriteExternal(ObjectOutput out)Method, then
ObjectOutputStream call a Object wiriteExternal(ObjectOutput out)Serialize the method of
ObjectInputStream call a Object readExternam(ObjectInput in)Serialize the method of''
 ----JDK Steps of serialization in class library--1--Create an object output stream, which can wrap a strange type of target output stream, such as file output stream:
objectOutputStream oos=new objectOutputStream(new FileOutStream(c:\\object.out));--2--Output stream through object writeObject()Method write object:
oos.writeObject(new a("xiaoxiao","145263","female"));
----JDK Steps of deserialization in class library--1--Create an object input stream that can wrap another type of input stream, such as file input stream:
objectInputStream ois=new ObjectInputStream(new FileInputStream("object.out"));--2--Output stream through object readObject()Method to read the object:
a aa=(a)ois.readObject();--3--In order to read data correctly and complete deserialization, it is necessary to ensure that the order of writing objects to the object output stream is consistent with the order of reading objects from the object input stream



2. How to output files and file directories under a folder with recursive algorithm


 public class TestFile {
    public static void main(String[] args) {
        File f=new File("D:\\shixun");
    public static void printFile(File file,int level) {
        //Print hierarchy of tree
        for(int i=0;i<level;i++) {
        //Name of output directory or file
        if(file.isDirectory()) {//Determine whether file is a directory
            File [] listFiles=file.listFiles();
            for(File temp:listFiles) {
                //Call yourself


3. 8 common methods of object

getClass(), hashCode(), equals(), clone(), toString(), notify(), notifyAll(),  wait(), finalize()


1.servlet life cycle

Servlet The life cycle consists of three parts: 1.initialization: Web Container loading servlet,call init()Method 2.Process request: when the request arrives, run its service()method. service()The automatic dispatch operation corresponds to the request doXXX(doGet perhaps doPost)method. three.Destruction: end of service, web The container will call servlet of distroy()Method destruction servlet. 

2. What are thread safe in map


JAVA Thread safe in map yes: Hashtable,synchronizedMap,ConcurrentHashMap. 
java in map How to realize thread safety in:
Synchronous map namely Hashtable, concurrenthashmap. 
You see Hashtable Is directly in hashmap With a lock on it, concurrenthashmap It is divided into multiple segmented locks.
java Thread safety level in Code:
Absolute thread safety.
In any environment, the caller does not need to consider additional synchronization measures, which can ensure the correctness of the program.
This definition is very strict, java There are few classes that meet this requirement, which is very important for implementation jsr133 Norms( java Memory model) jdk(Generally refers to jdk5.0 Above), general invariant classes meet Jedi thread safety. such as String,Integer Class. In general, if all fields in a class are final It is generally believed that this class is invariant. Invariant classes are absolutely thread safe.
Relative thread safety   
In general, the caller does not need to consider thread synchronization. In most cases, it can run normally. jdk Most of the classes are relatively safe. The most common example is java inside Vector Class.



3. What kind of files are uploaded to receive

Shangzhe Intelligence:

1. What is a business and what is its role


A transaction is a unit of work with the following attributes: 
A transaction is to be completed or undone completely and unambiguously. In case of an error in any operation, the effect of all operations constituting the transaction must be revoked, and the data shall be rolled back to the previous state. 
A transaction should protect all invariant attributes defined on the data(For example, integrity constraints). When a successful transaction is completed, the data should be in a consistent state. In other words, a transaction should transform the system from a consistent one-State transitions to another consistent state. For example, in the case of relational databases, 
A consistent transaction will protect all integrity constraints defined on the data. 
In the same environment, multiple transactions may be executed concurrently, and each transaction should be executed independently. Serial execution of a series of transactions should have the same effect as concurrent execution of them. This requires two things: 
During the execution of a transaction, the intermediate of data(May be inconsistent)State should not be exposed to all other transactions. 
Two concurrent transactions should not operate on the same data. Database management systems usually use locks to achieve this feature. 
The effect of a completed transaction should be lasting.



2.SQL optimization scheme


1.To optimize the query, we should try to avoid full table scanning. First, we should consider where and order by Index the columns involved.
2.It should be avoided as far as possible where Clause null Value judgment, otherwise the engine will give up using the index and scan the whole table, such as: select id from t where num is null
Can be in num Set the default value of 0 on the table to ensure that num Column no null Value, and then query as follows: select id from t where num=0
3.It should be avoided as far as possible where Used in Clause!=or<>Operator, otherwise the engine will abandon the use of index and perform a full table scan.
4.It should be avoided as far as possible where Used in Clause or Otherwise, the engine will give up using the index and perform a full table scan, such as: select id from t where num=10 or num=20
The query can: select id from t where num=10
union allselect id from t where num=20 and not in Also use it with caution, otherwise it will lead to full table scanning, such as: select id from t where num in(1,2,3)
For continuous values, you can use between Don't use it in The following: select id from t where num between 1 and 3
6.The following query will also result in a full table scan: select id from t where name like '%abc%'
7.It should be avoided as far as possible where Clause, which will cause the engine to abandon the use of indexes and perform a full table scan. For example: select id from t where num/2=100
Should read:select id from t where num=100*2
8.It should be avoided as far as possible where Clause, which will cause the engine to give up using the index and scan the whole table. For example: select id from t where substring(name,1,3)='abc'--name with abc initial  id
Should read:select id from t where name like 'abc%'
9.Don't be where In Clause“="Perform function, arithmetic operation or other expression operation on the left, otherwise the system may not use the index correctly.
10.When using an index field as a condition, if the index is a composite index, the first field in the index must be used as a condition to ensure that the system uses the index,
Otherwise, the index will not be used, and the field order should be consistent with the index order as much as possible.
11.Do not write meaningless queries. For example, you need to generate an empty table structure: select col1,col2 into #t from t where 1=0
If such code will not return any result set, but will consume system resources, it should be changed as follows:
create table #t(...)
12.It is often used exists replace in Is a good choice: select num from a where num in(select num from b)
Replace with the following statement: select num from a where exists(select 1 from b where num=a.num)
13.Not all indexes are valid for queries, SQL Query optimization is based on the data in the table. When there is a large amount of duplicate data in the index column, SQL Queries may not take advantage of indexes,
If there are fields in a table sex,male,female Almost half each, so even in sex The index built on the database also has no effect on the query efficiency.
14.The index is not the more the better, the index can certainly improve the corresponding efficiency select But it also reduces the efficiency insert and update Efficiency,
because insert or update The index may need to be rebuilt carefully depending on the specific situation.
The index number of a table should not exceed 6. If it is too many, consider whether it is necessary to build an index on some infrequently used columns.
15.Try to use numeric fields. If the fields containing only numerical information are not designed as characters, it will reduce the performance of query and connection and increase the storage overhead.
This is because the engine will compare each character in the string one by one when processing queries and connections. For numeric types, only one comparison is enough.
16.Use as much as possible varchar replace char ,Because first, the storage space of variable length fields is small, which can save storage space,
Secondly, for queries, the search efficiency in a relatively small field is obviously higher.
17.Don't use it anywhere select * from t ,Replace with a specific list of fields“*",Do not return any fields that you cannot use.
18.Avoid frequent creation and deletion of temporary tables to reduce the consumption of system table resources.
19.Temporary tables are not unusable. Using them appropriately can make some routines more effective, for example, when you need to repeatedly reference a dataset in a large table or common table. However, for one-time events, it is best to use the export table.
20.When creating a new temporary table, if the amount of data inserted at one time is large, it can be used select into replace create table,Avoid causing large log ,
To increase speed; If the amount of data is small, in order to alleviate the resources of the system table, you should first create table,then insert. 
21.If temporary tables are used, be sure to explicitly delete all temporary tables at the end of the stored procedure truncate table ,then drop table ,This can avoid long-term locking of system tables.
22.Avoid using cursors as much as possible because the efficiency of cursors is poor. If the data operated by cursors exceeds 10000 rows, rewriting should be considered.
23.Before using cursor based methods or temporary table methods, you should first find a set based solution to solve the problem. Set based methods are usually more effective.
24.Like temporary tables, cursors are not unusable. Use for small datasets FAST_FORWARD Cursors are often superior to other row by row methods, especially when several tables must be referenced to obtain the required data.
Routines that include "totals" in the result set are typically executed faster than using cursors. If development time permits, both cursor based and set based methods can be tried to see which method works better. twenty-five.Try to avoid large transaction operations and improve the concurrency of the system. twenty-six.Try to avoid returning large amounts of data to the client. If the amount of data is too large, consider whether the corresponding requirements are reasonable.



3.JAVA Memory Model


Program counter: thread private; Record the position of instruction execution;
Virtual machine stack: thread private; The life cycle is consistent with the thread; Store local variable table, operand stack, dynamic link, method exit and other information.

Local method stack: thread private; Used for virtual machines Native Service method.
Heap: thread sharing; JVM The largest area in the managed memory, mainly storing object instances and arrays;
Method area: thread sharing; Store class information, constants, static variables, code compiled by the real-time compiler and other data that have been loaded by the virtual machine.

4. Common function methods in JS


1:Conventional writing//Writing method of function
function run{
 alert("Conventional writing") //Here is the content of your function
2:Anonymous function writing var run = function(){
    alert("This is a way of writing declarative functions,On the left is a variable,On the right is the expression of a function,
  It means that the expression of an anonymous function is assigned to a variable myrun,It just declares a variable and points to a function object")//Here is the content of your function
3:Treat method as an object//As the object method and function writing method, two functions are created here, wrapped with {} var Text ={
    run1 : function(){
        alert("This must be placed inside an object,It's wrong to put it outside")//Here is the function content
    run2 : function(){
        alert("This must be placed inside an object,It's wrong to put it outside")//Here is the function content
Text.run1()//Call the first function
Text.run2()//Call the second function
4.Add method to object in constructor 
javascript Each object in the has prototype Properties, Javascript Of objects in prototype Property is interpreted to return a reference to an object type prototype.
// Add method var funName = function() {} to the object;
  funName.prototype.way = function(){
        alert('This is in funName Function is added to the original object way Method, used in constructor');
    // call
    var funname = new text();// create object
    funname.way();//Call object properties
5.Self executing function
js Self executing function found several different ways to write, put it up for you to see//Method 1: add parentheses at the beginning and end 
); /*This is jslint The advantage of the recommended writing method is that it can remind those who read the code that the code is a whole. 
For example, in an editor with syntax highlighting and matching function, when the cursor is behind the first left bracket, the last right bracket will also be highlighted. People who look at the code can see the whole at a glance. */
//Method 2: put parentheses outside function 
(function(){alert(1);})(); //This approach has one less benefit of code integrity than method 1.
//Method 3: add an operator in front of function, which is common! And void.
!function(){alert(1);}(); void function(){alert(2);}(); 


5. How to use exceptions and what are the exceptions


Basically, all exceptions belong to Throwable In general, it can be divided into Error(Error) and Exception(Exception). Eror Is an exception that the program cannot handle. When an exception occurs Error The program thread terminates when. In our general sense, the exception refers to Exception,This is also a question often asked by interviewers.
Let's briefly talk about Exception(Hereinafter referred to as exception).
Exceptions are divided into runtime exceptions( RuntimeException,It is also called non check time exception) and non run time exception (also called check exception). Common runtime exceptions are listed below:
NullPointerException - An attempt was made to access a variable, method, or element of an empty array of an empty object
ArrayIndexOutOfBoundsException - Array out of bounds access
NoClassDefFoundException - JAVA The runtime system cannot find the referenced class
ArithmeticException - In arithmetic operations, division by 0 or modulo
ArrayStoreException - Data storage exception. Object or data type is incompatible when writing array
ClassCastException - Type conversion exception
IllegalArgumentException - Invalid parameter for method
IllegalThreadStateException - An attempt to illegally change the state of a thread, such as trying to start a running thread
NumberFormatException - Abnormal data format, trying to convert a string into a numeric value illegally (or vice versa)
SecurityException - If Applet Attempt to execute a WWW Actions prohibited by browser security settings
IncompatibleClassChangeException - If you change the definition of a class without recompiling other objects that reference this class. For example, the declaration of a member variable is changed from static to non static, but other classes that reference this variable are not recompiled, or vice versa. For example, a field or method in the class declaration is deleted, but the classes that reference this field or method are not recompiled
OutOfMemoryException - Out of memory, usually at the time of object creation
IncompatibleTypeException - Trying to instantiate an interface, Java The system will throw this exception at runtime
UnsatisfiedLinkException - If the method to be called is C Function, but Java The runtime system cannot connect to this function
InternalException - The abnormal condition caused by the internal fault of the system may be due to Java The reason of the system itself at runtime. If you find a reproducible InternalException,You can give it directly Sun Company email.



6. AOP and IOC in spring


IOC:Inversion of control is also called dependency injection. Using factory mode
Give the object to container management. You just need to spring The configuration file always configures the corresponding bean,And set relevant properties to make spring Container to generate instance objects and management objects of classes. stay spring When the container starts, spring You will be configured in the configuration file bean All are initialized, and then when you need to call, you can initialize those already initialized bean Assign to those you need to call bean Class (assuming that the class name is A),The method of allocation is to call A of setter Method to inject, without requiring you to A inside new these bean Yes.
Note: during the interview, if you have conditions, draw pictures, which makes it more obvious that you understand.
AOP:Aspect oriented programming. ( Aspect-Oriented Programming)
AOP It can be said to be right OOP Supplement and perfection of. OOP The concepts of encapsulation, inheritance and polymorphism are introduced to establish an object hierarchy to simulate a set of public behaviors. When we need to introduce public behavior for decentralized objects, OOP Is powerless. in other words, OOP It allows you to define the relationship from top to bottom, but it is not suitable to define the relationship from left to right. For example, log function. Log code is often spread horizontally across all object levels, regardless of the core functions of the objects it spreads. stay OOP In the design, it leads to a large number of code duplication, which is not conducive to the reuse of each module.
Encapsulate the cross business logic (such as security, log, transaction, etc.) in the program into a facet, and then inject it into the target object (specific business logic).
realization AOP The technology is mainly divided into two categories: one is to use dynamic agent technology to decorate the message by intercepting the message to replace the execution of the original object behavior; The second is to use the way of static weaving and introduce specific syntax to create "aspects", so that the compiler can weave the code related to "aspects" during compilation.



7.JDK1.8 what are the new features


1,default Keyword 2 Lambda Expression 3. Functional interface 4.Method and constructor reference 5. Local variable restriction 6 Date Api Update 7. Flow



Jiangsu Jinmao e-commerce:

1. How does java realize that only one user can log in for an account, and others cannot log in


1 .When a user logs in, the user is added to a ArrayList Middle 2 .View when logging in again ArrayList If there is no such user in the ArrayList If the user already exists in, it is blocked from logging in 3 .When the user exits, you need to exit from the ArrayList Delete the user in the, which can be divided into three cases
① Use the logout button to exit normally
② Click the browser close button or use Alt+F4 Exit, you can use JavaScript Capture the closing event of this page,
Execute a paragraph Java Method delete ArrayList Users in
③ Abnormal exit, such as client system crash or sudden crash, can be used every other period of time session Delete the without activity session The corresponding user, so that the user can log in normally after waiting for a period of time.



2.SQL query method for duplicate data in a table


1.After all the data are queried and grouped, the query data and the number of repetitions of the duplicate data are listed below first: select  count(username) as 'Number of repetitions',username from xi group by username  having count(*)>1 order by username desc2.Find redundant duplicate records in the table. Duplicate records are based on a single field( peopleId)To judge select * from peoplewhere peopleId in (select  peopleId  from  people  group  by  peopleId  having  count(peopleId) > 1)3.Redundant duplicate records (multiple fields) in the lookup table select * from people awhere (a.peopleId,a.seq) in  (select peopleId,seq from people group by peopleId,seq  having count(*) > 1)



3. How to realize batch update


--Create table
create table test1
  a varchar2(100),
  b varchar2(100)
create table test2
  a varchar2(100),
  b varchar2(100)
);--Insert statement 
declare i number; 
beginfor i in 1..10 loop  
insert into test1(a,b)values(i,i);
end loop; for i in 1..5 loop  
insert into test2(a,b)values(i,i||i);
end loop; 
end; --Check: select t.*,t.rowid from test1 tselect t.*,t.rowid from test2 t  --How to update all:
update test1 t1set t1.b = (select t2.b from test2 t2 where t1.a = t2.a) --If there is no following statement, the result will be different. Please note where exists
(select '' from test2 t2 where t1.a = t2.a);--Start batch update
 countpoint number := 0;
 for row_id in (select t1.rowid,t2.b from test1 t1,test2 t2 where t1.a = t2.a) loop
  update test1 t1
    set t1.b = row_id.b
   where t1.rowid = row_id.rowid;
  countpoint := countpoint + 1;
  if mod(countpoint, 5) = 0 then
   dbms_output.put_line('countpoint:' || countpoint);
  end if;
 end loop;
end;  --Delete data
delete test1;
delete test2;--Delete table
drop table test1;
drop table test2; 



4. What type of parameters are put in the switch function

jdk1.7 Previous version switch(expr1)In, expr1 Is an integer expression, which can be int Basic type or Integer Packaging type, due to, byte,short,char Can be implicitly converted to int,

Therefore, these types and packaging types of these types are also possible. So pass it on to switch and case The argument to the statement should be int, short, char perhaps byte,also enum. long,string Can't work on swtich. 
stay jdk 1.7 in switch The parameter type of can be string type.


Nanjing Shuzu company:

1. What are Java containers


array,String,java.util Collection container under
Array length is limited to Integer.Integer.MAX_VALUE;
String Length limit of: The bottom is char Array length Integer.MAX_VALUE Thread safe
List:Orderly storage,List storage,Element repeatable
Set:disorder,Element cannot be repeated
Map:disorder,Element repeatable



2. I have used the third-party payment interface, but I haven't talked about it

3. Differences between hashtable and hashmap


 1,The inherited parent class is different
      Hashtable Inherited from Dictionary Class, and HashMap Inherited from AbstractMap Class. But both have been achieved Map Interface.
      2,Different thread safety
      javadoc About hashmap This implementation is not synchronous. If multiple threads access a hash map at the same time, and at least one of them structurally modifies the map, it must maintain external synchronization.
      Hashtable The method in is Synchronize Yes, and HashMap The method in is by default yes No Synchronize of In a multithreaded concurrent environment, it can be used directly Hashtable,You don't need to synchronize its methods yourself,

      But use HashMap You must add synchronization processing yourself. (structural modification refers to any operation of adding or deleting one or more mapping relationships; only changing the value associated with the key already contained in the instance is not structural modification.)

      This is generally accomplished by synchronizing the objects that naturally encapsulate the mapping. If such an object does not exist, it should be used Collections.synchronizedMap Method to "wrap" the mapping. It's best to do this when creating,

      To prevent accidental asynchronous access to the map.

      Map m = Collections.synchronizedMap(new HashMap(...));
      Hashtable Thread safety is well understood because it is added to every method Synchronize. Let's analyze it here HashMap Why are threads unsafe:
      HashMap The bottom is a Entry Array, when hash In times of conflict, hashmap It is solved by linked list. The head node of the linked list is stored in the corresponding array position. For the linked list, the newly added node will be added from the original node.



4.red3is persistence


RDB Persistence: this mechanism can generate point in time snapshots of data sets within a specified time interval( point-in-time snapshot). 
AOF Persistence: records all write commands executed by the server, and restores the dataset by re executing these commands when the server starts. AOF
All commands in the file are Redis The new command will be appended to the end of the file. Redis You can also do it in the background AOF file
Rewrite( rewrite),bring AOF The volume of the file does not exceed the actual size required to save the dataset state
No persistence: make the data exist only when the server is running.
Simultaneous application AOF and RDB: When Redis When restarted, it takes precedence AOF File to restore the dataset because AOF File saved
Data sets are usually smaller than RDB The data set saved by the file is more complete



5.hashmap thread is unsafe. How to make it safe

6. What if redis crashes when token is saved in redis

7.mycat sub database and sub table


  Transparent to business, partition just divides the file storing data into many small pieces, such as mysql One table in corresponds to three files.MYD,MYI,frm. 
Put the data file according to certain rules(MYD)And index files( MYI)The partitioned table is still a table. Partitions can distribute tables to different hard disks, but not to different servers.
Advantages: there are no multiple copies of data, so there is no need for data replication, and the performance is higher.
Disadvantages: the partition strategy must be fully considered to avoid the correlation of data between multiple partitions. Each partition is a single point. If a partition goes down, it will affect the use of the system. 2. Slice
  It is transparent to the business. In terms of physical implementation, it is divided into multiple servers, and different partitions are on different servers. as HDFS. 3,Sub table
Same database sub table: all sub tables are in the same database. Since the table names in the database cannot be repeated, it is necessary to change the data table names into different names.
Advantages: because they are all in one database, common tables do not need to be copied, and the processing is simpler.
Disadvantages: because it is still in a database, CPU,Memory, file IO,network IO And other bottlenecks still cannot be solved, and can only reduce the number of data records in a single table. Inconsistent table names will lead to complex subsequent processing (refer to mysql meage Storage engine to process)
Different databases and tables: because the tables are in different databases, the same table name can be used at this time.
advantage: CPU,Memory, file IO,network IO And other bottlenecks can be effectively solved. With the same table name, it is relatively simple to handle.
Disadvantages: since public tables are used in all sub tables, they need to be copied and synchronized. Some aggregation operations, join,group by,order And so on. 4. Sub Library
  Table splitting and partition are based on the data separation skills in the same database, which improves the performance of the database to a certain extent. However, with the increase of business data, all data is in one database,

network IO And documents IO Are concentrated on one database, so CPU,Memory, file IO,network IO May become a system bottleneck.
When the data capacity of the business system approaches or exceeds the capacity of a single server QPS/TPS Approaching or exceeding the processing limit of a single database instance, etc. At this time, it is often the combination of vertical and horizontal data splitting methods to distribute data services and data storage to multiple database servers.
Sub database is just a popular term. The more standard name is data fragmentation, which is implemented by a method similar to the guidance of distributed database theory, so as to achieve full transparency of data service and data storage for applications



8. Common linux commands
  1. How spring MVC works and notes

1. The user sends a request to the front-end controller DispatcherServlet.


2. The dispatcher servlet receives a request to call the handler mapping processor mapper.


3. The processor mapper finds the specific processor (which can be found according to the xml configuration and annotation), generates the processor object and the processor interceptor (if any) and returns it to the dispatcher servlet.


4. Dispatcher servlet calls HandlerAdapter processor adapter.


5. The HandlerAdapter calls the specific processor (Controller, also known as back-end Controller) through adaptation.


6. The Controller returns ModelAndView after execution.


7. The HandlerAdapter returns the ModelAndView of the controller execution result to the dispatcher servlet.


8. DispatcherServlet passes ModelAndView to viewrestrover view parser.


9. The viewrestrover returns the specific View after parsing.


10. The dispatcher servlet renders the View according to the View (that is, fills the View with model data).


11. Dispatcher servlet responds to the user.


10. Common notes of springboot


1,@Component: Put it on the class and instantiate the ordinary class to spring In the container. It can be said that many annotations are based on this annotation.
2,@Bean:  Put it on the method and use it@Bean Annotation method is equivalent to XML Medium configuration bean,This method generally returns an entity object and tells spring An object is generated here, and then the object is handed over to Spring Administration. The method that generates this object Spring It will only be called once, and then this Spring Will this Bean Object in its own container.
3,@Configuration: Mark that the current class is a configuration class, and one or more declared in the current class will be@Bean Examples of annotation marked methods are incorporated into srping Container, and the instance name is the method name. (actually, it depends on@Component (note)
4,@ConfigurationProperties: Map the parameters in the configuration file into an object through prefix To set the prefix, and then match the following with the attribute name of the object to realize the injection (of course, the attributes of the object to be injected need to be provided) get and set method - - - because spring The bottom layer actually calls the object through reflection set Method)




ZooKeeper Is a distributed, open source distributed application coordination service Google of Chubby An open source implementation is Hadoop and Hbase Important components of.

It is a software that provides consistency services for distributed applications. Its functions include configuration maintenance, domain name service, distributed synchronization, group service and so on.
ZooKeeper The goal of is to encapsulate complex and error prone key services and provide users with simple and easy-to-use interfaces and efficient and stable systems.
ZooKeeper Contains a simple primitive set, [1]  provide Java and C Interface for.
ZooKeeper In the code version, the interfaces of distributed exclusive lock, election and queue are provided $zookeeper_home\src\recipes. There are distributed locks and queues Java and C Two versions, election only Java edition.


Jiawa network:

1. The difference between ArrayList and LinkedList

ArrayList It is a dynamic array structure with index and fast query (time complexity) O(1)),Slow addition and deletion (because the index needs to be moved)
LinkedList It is a linked list structure with no index and pointers to the front and back. The query needs to look down from the beginning (time complexity) O(n)),Fast addition and deletion (you only need to modify the pointer in the linked list without moving others)

2. Functions of requestbody and resourceBody

It is mainly used to receive the data passed from the front end to the back end json Of data in a string(Of data in the request body);


3. How to upload files

4. How to implement timed tasks in Java


ordinary thread
This is the most common way to create one thread,Then let it in while It runs all the time in the cycle, through sleep Methods to achieve the effect of timed tasks. This can be implemented quickly and simply.
use Timer and TimerTask
The above implementation is very fast and simple, but it also lacks some functions.
use Timer and TimerTask Compared with the above methods, it has the following advantages:
It can be controlled when starting and canceling tasks
The first time you perform a task, you can specify what you want delay time
When implemented, Timer Class can schedule tasks, TimerTask Is through run()Method to achieve specific tasks.
Timer Instance can schedule multiple tasks, which is thread safe.
When Timer When the constructor of is called, it creates a thread that can be used to schedule tasks:
ScheduledExecutorService Is from Java SE 5 of java.util.concurrent As a concurrent tool class, it is the most ideal way to implement timed tasks.
Compared with the above two methods, it has the following advantages:
Compared to Timer Single thread, which executes tasks through thread pool
Can be very flexible to set the first execution task delay time
A good agreement is provided to set the execution time



5. What are the file streams

Byte stream and character stream

Zhongke soft 

1. Is String the most basic data type? What is the difference between String and StringBuffer?


no Java There are only 8 basic data types in: byte,short,int,long,float,double,char,boolean,Except basic type( primitive type),The rest are reference types( reference type),Enumeration type( enumeration type)It is also a reference type. among byte One byte, short Two bytes, int Four bytes, long Eight bytes, char Two bytes.

(1)String:Is the object not the original type.Is immutable,Once created,You can't change its value.For existing String Object modification is to recreate a new object,Then save the new value.String yes final class,That is, it cannot be inherited.
(2)StringBuffer:Is a mutable object,When you modify it, it won't be like String Then recreate the object. It can only be built through the constructor. After the object is built,Memory space is allocated in memory,And initially save one null.towards StringBuffer You can use it when you pay the value append method.


2. What's the difference between int and Integer?

int Is the basic data type, Integer Is the reference data type;
int The default value is 0, Integer The default value is null;
int Type stores values directly, Integer You need to instantiate the object and point to the address of the object.

3. What are the similarities and differences between runtime exceptions and general exceptions?


1.Different definitions, runtime exceptions are RuntimeException Class and its subclasses are abnormal, such as NullPointerException,IndexOutOfBoundsException Wait. The general exception is RuntimeException Exceptions other than are of type Exception Class and its subclasses. two.The handling methods are different. The runtime exception does not check the exception. The program can choose to capture and handle it or not. For general exceptions, JAVA The compiler forces the user to correct these exceptions catch And processing, otherwise the program cannot be compiled. three.The causes are different. Runtime exceptions are generally caused by program logic errors. Programs should avoid such exceptions as much as possible from a logical point of view. In the face of this anomaly, whether we like it or not, we can only write a lot by ourselves catch Block to handle possible exceptions.


4. Tell the life cycle of Servlet and the difference between Servlet and CGI?


When the server starts(web.xml Medium configuration load-on-startup=1,The default is 0)Or ask for the first time servlet When, one is initialized Servlet Object, that is, the initialization method will be executed init(ServletConfig conf),Should servlet Object to handle all client requests, service(ServletRequest req,ServletResponse res)Method, and will be destroyed only when the server is shut down servlet Object, executing destroy()method.
Difference: 1)Good portability. because Java The language has the characteristics of cross platform and strong portability Sevlet It also has good portability, that is, it can be deployed to many different types of software without modifying the code Web On the server. two)High execution efficiency. because CGI For each request, a process is created to process, and Servlet Create a thread for each request to execute, and the cost of creating a thread is less than that of creating a process CGI comparison, Servlet In the process of interaction, it has shorter response time and higher response efficiency. three)Powerful. Servlet Can be with Web The server interacts, and CGI But I can't communicate with you Web The server interacts directly. four)Easy to use. Servlet It provides many very useful interfaces for reading or setting HTTP Header message, processing Cookie And tracking session status, etc. five)Strong scalability. because Servlet By Java Language, so it has Java All the advantages of language


5. State the storage performance and characteristics of ArrayList, vector and LinkedList.

ArrayList and Vector Both use the array method to store data. The number of array elements is greater than the actual stored data, so as to add and insert elements. They all allow to index elements directly by serial number, but inserting elements involves memory operations such as array element movement, so indexing data is fast and inserting data is slow, Vector Due to the use of synchronized Methods (thread safe),
Generally, the performance is relatively low ArrayList Poor, and LinkedList The bidirectional linked list is used for storage. The data indexed by serial number needs to be traversed forward or backward, but when inserting data, only the front and rear items of this item need to be recorded, so the insertion speed is fast.


Zhongke software:

1.struts core controller

ServletAction Inherit from HttpServlet,yes struts1.x Neutralize the core controller.
Struts 2:
FilterDispatcher yes Struts 2 The core controller of the framework, which acts as a Filter Run in Web In the application, it is responsible for intercepting all user requests. When the user request arrives, the Filter User requests are filtered. If the user requests to action At the end, the request will be transferred to Struts 2 Frame processing.


2. Which of hibernate and mybatis is easy to use and why is the thread implementation method


JSTL(Java server pages standarded tag library,Namely JSP Standard label Library) JCP The standard specifications formulated, which are mainly provided to Java Web Developers a standard general label library, developers can use these labels to replace JSP On page Java Code, so as to improve the readability of the program and reduce the difficulty of program maintenance.


4. Assemble

The collection has two parent interfaces, one collection,One Map;
and collection There are two sub interfaces, one List,One Set;
List There are two common implementation classes ArrayList,LinkedList;
Set There are two common implementation classes HashSet,TreeSet;
Map There are two common implementation classes HashMap,HashTable. 


5. Filter interceptor

1.Filter( Filter): Filter is the function of filter, in web Filter some of our specified in development url,For example, intercept the interface requests we don't need and modify the requests( request)And response( response)Content, complete CORS Cross domain request, etc.Interceptor( Interceptor): It is aspect oriented programming(AOP,Aspect Oriented Program)of Is in Service Or call a method before a method, or call a method after method. For example, dynamic agent is a simple implementation of interceptor. It can print out the string before calling the method (or do other business logic operations), or print out the string after calling the method, or even do business logic operations when throwing exceptions.


6.jsp built-in object


1,request object
request This object represents the request information 2 response object
response Represents the response to the client, 3 session object
session Object is an object automatically created by the server and related to user requests. 4, application object
 application Object can save the information in the server until the server is shut down out object
out Object used in Web Output information in the browser and manage the output buffer on the application server. 6, pageContext object
pageContext Object is used to obtain parameters in any range config object
config The main function of the object is to obtain the configuration information of the server. 8, page object
page Object representation JSP Itself, only in JSP Inside the page is legal. 9, exception object
exception Object is used to display exception information



7. Four scopes

1.    page field:    Only in the current jsp Page usage                (Current page)  2.    request field: Can only be used in the same request               (forward)  3.    session field: Only in the same session(session object)Used in  (Private)  4.    context field: Only in the same web Used in application            (Global)




AJAX It can make web pages update asynchronously. This means that a part of a web page can be updated without reloading the whole web page.

Zhongke soft

1. One single case



Singleton mode
public class Singleton {
private Singleton(){
private static volatile Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
return instance;





2. Introduce thread deadlock


Thread deadlock: when threads wait or restrict each other with global semaphores for safety and synchronization, when the program enters a deadlock state (both threads are stopped), it is called thread deadlock.




3. What's the use of Ajax



type: "POST",
url: "ShowProduct.aspx/GetDHList",
data: '{CategoryId:"' + CategoryId + '"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
var item = eval(data.d);
var StrHtml = "";for (var i in item) {}
}, async: false
$.ajax({ url: "test.html", context: document.body, success: function(){





4.XML parsing method



DOM(Document Object Model) Generation and parsing XML file. from W3C Provides an interface that will the entire XML Read the document into memory and build a DOM Tree for each node(Node)Operate.
SAX(Simple API for XML) Generation and parsing XML file. SAX Instead of loading the entire document into memory, it is event driven API(Observer pattern),Users only need to register the events they are interested in.
DOM4J Generation and parsing XML file. dom4j Yes, currently xml The analytical aspect is the best(Hibernate,Sun of JAXM Also used dom4j To analyze XML),It combines many beyond the basic XML Functions represented by documents, including integrated XPath Support XML Schema Support and event based processing for large documents or streaming documents
JDOM Generation and parsing XML .  JDOM And DOM Very similar, it is processed XML Pure JAVA API,API Extensive use Collections Class, and JDOM Use only concrete classes, not interfaces.





5.JDK and JRE



JDK And JRE Differences between
JRE:  Java Runtime Environment
JDK: Java Development Kit
JRE As the name suggests java Runtime environment, including java Virtual machines, java Basic class library. Is to use java The software environment required for the operation of programs written in language is provided to those who want to run java Used by the user of the program.
JDK As the name suggests java Development kit is used by programmers java Language writing java The development kit required by the program is provided to programmers. JDK Contains JRE,It also includes compilation java Source code compiler javac,It also contains a lot java Tools for program debugging and analysis: jconsole,jvisualvm And other tool software, which also includes java Documentation and documentation required for programming demo Example program.





6. Memory recycling mechanism


The standard of memory allocation and memory recovery is eight words: generation allocation and generation recovery.
Because strings, objects and arrays have no fixed size, dynamic storage allocation can only be carried out when their size is known. JavaScript Every time a program creates a string, array, or object, the interpreter must allocate memory to store that entity. As long as memory is allocated dynamically like this, it will eventually be released so that they can be reused.

7. Breakpoint shortcut



Shortcut key function description 
F8 Single step debugging without entering the function 
F7 Single step debugging, enter the function 
Shift+F7 Select the function to enter 
Shift+F8 Jump function 
Alt+F9 Run to breakpoint 
Alt+F8 Execute expressions to view results 
F9 Continue execution, enter the next breakpoint or finish executing the program 
Ctrl+F8 set up/Cancel current line breakpoint 
Ctrl+Shift+F8 View breakpoints





8. Automatic unpacking


Automatic packing is to automatically convert the basic data type to the wrapper type; Automatic unpacking is to automatically convert the wrapper type to the basic data type




jQuery Is a fast and concise JavaScript Frame, which encapsulates JavaScript Common function codes provide a simple JavaScript Design pattern, optimization HTML Document manipulation, event handling, animation design and Ajax Interaction.




10. Principles of JSP instruction and action



Three instructions:
taglib Label instruction
Six actions:< jsp:include > Dynamic inclusion< jsp:forward> Request forwarding < jsp:param> Set request parameters< jsp : useBean> 
< jsp : setProperty> Assign a value to the specified object property < jsp : getProperty >Gets the property value of the specified object 






Zhongke soft

1. How to define CSS Style


1.Create a new one HTML page,Named test.html,Used for CSS Description of the style definition. two.stay test.html Page definition div element,And pass<style type="text/... div definition CSS style,You can use elements directly div Implement style definitions as selectors.


String sql = 
     "select * from " +  
     (select *,rownum rid from (select * from students order by postime desc) where rid<=" + pagesize*pagenumber + ") as t" + 
     "where t>" + pageSize*(pageNumber-1);




3.8 basic types






4. The difference between final, finally and finalize



I final : 1,Modifier (keyword) if a class is declared as final,This means that it can no longer derive new subclasses and cannot be inherited as a parent class. 2. Declare a variable or method as final,It can ensure that they are not changed in use. Declared as final The variable of must be given an initial value at the time of declaration, and can only be read in subsequent references and cannot be modified. It is declared as final Methods can only be used and cannot be overloaded.
II finally:
Provided during exception handling finally Block to perform clear operations. If an exception is thrown, the matching catch The statement will execute, and then the control will enter finally Block, if any.
III finalize: 
Is the method name. java Technical permission finalize()Method does the necessary cleanup before the garbage collector clears the object from memory. This method is called when the garbage collector determines that the cleaned object is not referenced.
finalize Yes Object Therefore, all classes in it inherit. Subclasses can override finalize()Method to sort out system resources or perform other cleaning work.





5. How to start a thread



inherit Thread Class 1.Custom class MyThread inherit Thread Class 2.MyThread Class override run method.
realization Runnable Interface 1.Custom class MyRunnable realization Runnable Interface 2.rewrite run()Method 3.establish MyRunnable Object of class 4.establish Thread Class, and pass the object created in step 3 as a construction parameter 5.Start thread





6. Why is java cross platform


because Java The compiled code is not the code that can be run directly by the hardware system, but a kind of "intermediate code" - bytecode. Then different hardware platforms are installed with different Java virtual machine(JVM),from JVM To "translate" the bytecode into the code that can be executed by the corresponding hardware platform. So for Java For programmers, there is no need to consider what the hardware platform is. therefore Java Can cross platform.




7. Differences between get and post requests


1,    Get The requested data will be displayed in the address bar, and post The request will no longer be displayed in the address bar    Size of transmitted data
http Get The request has a limit on the data transmitted due to the browser's limit on the address length. and POST The request will not cause data transmission restrictions due to address length restrictions. 3,    Security,POST Is safer than GET High security. Because the data will be presented in the address, key information such as password can be found through history.




8. The difference between list and set


List It's orderly Collection. Java List There are three implementation classes: ArrayList,Vector and LinkedList. 
Set It is unique and non repeatable. The commonly used implementation classes are HashSet,TreeSet,LinkedHashSet




9. How to use HashMap


HashMap According to the key hashCode Value stores data. In most cases, its value can be directly located, so it has fast access speed, but the traversal order is uncertain. HashMap At most one record is allowed. The key is null,The value of multiple records allowed is null. HashMap Non thread safe.




10. How can ajax achieve synchronization and asynchrony


AJAX Medium basis async Different values are divided into synchronization( async = false)And asynchronous( async = true)





11. How to transfer files

The first method: send it to the specified interface in the form of string parameters to get its value (array is used for multiple)
The second method: adopt the streaming transmission mode to transmit the interface. This method can be transmitted in batches and has unlimited size. It supports the uploading of various types of files

 12.sevrlet life cycle


①Server loading Sevrlet. 
②establish Sevrlet,Only on request Sevrlet The construction method will be called to create an instance.
③init()Initialize, create Sevrlet Instance is called immediately after and executed only once.
④service()Processing user requests can be called many times, and each request will be called service Method, which is actually used to respond to the request.
⑤destory()Destroy, only called once, in the current Servlet Where WEB The application is called before being unloaded to release the current. Servlet Resources occupied


Duanmu company

1. How to use LIKE for fuzzy query in XML Mapping


1.Direct parameter transfer method direct parameter transfer method is the keyword to be queried keyword,Splice the format to be queried in the code, such as%keyword%,Then pass it directly as a parameter mapper.xml In the mapping file.
2.CONCAT()function MySQL of CONCAT()The function is used to connect multiple strings into one string, which is the most important mysql One of the functions.
3.use mybatis label<bind value='' name=''/>
4.stay mybatis in xml Configuration in file name LIKE '%${name}%' Or address LIKE "%"#{address}"%"



2. How to batch insert the incoming collection (collection < E >) in XML Mapping?, That is, how to generate the following SQL from the set?

INSERT INTO TABLE_NAME(a,b,c) VALUES (a1,b1,c1),(a2,b2,c2)

3. In XML Mapping, how to obtain the value generated by MYSQL AUTO_INCREMENT while inserting?

Using select last_insert_id()

@Insert("insert into table(content,questionid,active,submit,createtime) values(#{content},#{questionid},1,#{submit},#{createtime})")
    @SelectKey(statement="select last_insert_id()",before=false,keyProperty="_id",resultType=Integer.class,keyColumn="_id")
    int insertQuestionItem(QuestionItemInfo questionItemInfo);



 4. What is the biggest difference between BlockingQueue and ordinary Queue?


Blocking queue is different from ordinary queue in two points
1.When the blocking queue obtains elements, if the queue is empty, it will wait for the queue to have elements, otherwise it will block the queue (the normal queue returns results without elements)
2.When the blocking queue is put into the element, if the queue is full, wait for the queue until there is an empty location, and then insert. (ordinary queue, either directly expanded or directly unable to be inserted without blocking)
The best scenario for blocking queues is for producers and consumers to obtain and process the code without judgment (ordinary queues have to judge whether there are elements, blocking queues do not need to judge, and no elements will block until there is something)



5.Thread. What does the InterruptedException that sleep () may throw represent? How to deal with it?


When a method is declared later, it may be thrown InterruptedException In case of exception, it indicates that this method may take a little time, but can be cancelled.
throw InterruptedException The representative methods are:
1.Java.lang.Object Class wait method
2.Java.lang.Thread Class sleep method.
3.Java.lang.Thread Class join method.
Here we only see sleep method.
interrupt The method is Thread The instance method of class does not need to be obtained during execution Thread Instance locking. Any thread can call the of other threads through the thread instance at any time interrupt method. When in sleep The thread in is called interrupt Method, the suspended state is discarded and thrown InterruptException In this way, the control of the thread is handed over to the person who caught the exception catch Block.
Interrupt Function of method-------
interrupt Method just changes the interrupt state
sleep The method will constantly check the value of interrupt status and throw it by itself InterruptedException.
from Thread Provided and accepted Thread.sleep() and Object.wait() One kind of support mechanism is to cancel interruption; It allows one thread to request another thread to stop what it is doing. When a method is thrown InterruptedException It is telling you that if the thread executing the method is interrupted, it will try to stop what it is doing and return in advance by throwing InterruptedException Indicates that it returns early. Well behaved blocking library methods should be able to respond to interrupts and throw them InterruptedException,So that it can be used in cancellable activities without affecting the response.
Copyright notice: This article is CSDN Blogger「Silvia_flora」Original articles, follow CC 4.0 BY-SA Please attach the original copy of this Agreement and the link.
Original link:



6. How to implement a method that executes a task and sets a time limit. If the task can be completed within the limited time, the task execution result will be returned; otherwise, null will be returned? Write core code


ScheduledExecuterService service = Executors.newSinglThreadSchduledExecetor();
ScheduledFuture f = service.scheduleAtFixedDelay(task, initialDelay, period, time unit);
if currentDate = 00:00



a. Is there a problem with the following code in a multithreaded environment? If yes, how to correct it?

b. What does the volatile keyword in the following code mean? If deleted, how will it affect the code?


class Counter{
    private volatile int count = 0;
    public int getNext(){
        return ++count;    



8. In @ controller, what is the difference between jump ("redirect:url") and forward ("forward:url")?



1.From the address bar display
forward Is the server requesting the resource,The server directly accesses the destination address URL,Put that URL Read the response content of,Then send these contents to the browser.The browser has no idea where the content sent by the server comes from,So its address bar is still the original address.
redirect Is the server according to logic,Send a status code,Tell the browser to request that address again.So the address bar is new URL.2.In terms of data sharing
forward:The forwarded page and the page forwarded to can be shared request The data inside.
redirect:Cannot share data.3.In terms of application place
forward:It is generally used when users log in,Forward to the corresponding module according to the role.
redirect:It is generally used to return to the main page and jump to other websites when users log off and log in.4.In terms of efficiency








10. How to specify the loading order of beans when declaring beans with annotations (such as @ Component)?

@Primary annotation

When multiple beans of the same type need to be configured in the system, @ Primary can define the priority of these beans





11. How to specify multiple beans of the same type when using annotation injection?

@Qualifier annotation

When there are multiple beans of the same type in the system, @ Autowired does not know which implementation class to choose for dependency injection. At this point, we can use the @ Qualifier annotation to fine tune and help @ Autowired select the correct dependencies. The following is a code example of this annotation:


 . An example code will be given below to illustrate this feature:



Topics: Java Back-end