Summary of Java interview questions | Summary of Java interview questions 10- Feign and design pattern module (continuously updated)

Feign

How to communicate within the project

Add the @EnableFeignCleints annotation and @EnableDiscoveryClient to the startup class of the calling module

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-jYU2Tmn4-1683165926603) (D:/Study/JAVA/Interview/Interview Questions Organized Version.assets/image- 20220909084447460.png)]

Then register his service in nacos in the configuration file;

Integrate all called classes into the next module, then create a called class, add the annotation @FeignClient(value = “service-cmn”) to this class, and write the called service name in value. Copy the called method and write it in the form of an interface, and then write the complete interface address in the Mapping annotation; then inject the called module into the calling module;

Let’s take a closer look at what’s done inside the annotations. I won’t explain the internal methods of the annotation. If you don’t add it, there will be a default configuration.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(FeignClientsRegistrar.class)
public @interface EnableFeignClients {
    
    ...}

The first three annotations seem unremarkable, but the focus is on the fourth @Import. Generally, this annotation is used to dynamically register Spring Beans.

Spend a weekend to master the core principles of SpringCloud OpenFeign - Zhihu (zhihu.com)

Brief description of Feign principle

  • Start the Feign Starter component through the @EnableFeignCleints annotation
  • Feign Starter registers global configuration during project startup, scans all @FeignClient interface classes under the package, and registers IOC containers
  • When the @FeignClient interface class is injected, FactoryBean#getObjectthe dynamic proxy class is returned by
  • When the interface is called, it is intercepted by the dynamic proxy class logic, and the @FeignClient request information is generated through the encoder to generate a Request
  • Let Ribbon perform load balancing and select a healthy Server instance
  • Then the client carries the request and calls the remote service to return the request response.
  • Generate Response through the decoder and return it to the client, parsing the information flow into interface return data

The @EnableFeignClients annotation is added to the main program entrance to enable the FeignClient scanning and loading process. According to Feign Client's development specifications, define the interface and add @FeignClientd annotation.

When the program starts, it will perform package scanning, scan all @FeignClients annotated classes, and inject this information into the Spring IOC container. When the method in the defined Feign interface is called, it will be generated through the JDK proxy method. Specific RequestTemplate.

When generating a proxy, Feign creates a RequestTemplate for each interface method. When generating a proxy, Feign will create a RequestTemplate object for each interface method, which encapsulates all the information required for the HTTP request, such as request parameter names, request methods and other information are determined in this process.

Then the RequestTemplate generates the Request, and then hands the Request to the Client for processing. This means that the Client can be JDK's native URLConnection, Apache's HttpClient, or OKhttp. Finally, the Client is encapsulated into the LoadBalanceClient class, which is initiated in conjunction with Ribbon load balancing. calls between services.

Summarize:

Add @EnableFeignClients to the called microservice module. When starting the microservice, use the @EnableFeignClients annotation to start the Feign stater. Scan all @FeignClient annotated classes and register these classes in the IOC container through JDK dynamic proxy. Generate a specific RequestTemplate object, which encapsulates all the information requested by @FeignClient. The RequestTemplate object generates a request and hands it to Rabbin for load balancing. Rabbin selects a healthy server instance to complete the request and return a response;

Design Patterns

Design patterns used in spring

  • Factory pattern: BeanFactory/ApplicationContext is the embodiment of the simple factory pattern, used to create instances of objects;
  • Singleton mode: Bean defaults to singleton mode.
  • Agent mode: It can encapsulate logic or responsibilities (such as transaction processing, log management, permission control, etc.) that have nothing to do with the business but are jointly called by the business modules, so as to reduce the duplication of code in the system and reduce the coupling between modules . And it is conducive to future scalability and maintainability .
  • Template method: Used to solve the problem of code duplication. For example, RestTemplate, jdbcTemplate, JpaTemplate and other classes ending with Template that operate on the database use the template mode.

What design patterns were used in the project scenario?

Login function-strategy mode is used

Strategy Pattern, also called policy pattern, is a relatively simple pattern. Its purpose is to define a set of algorithms, encapsulate each algorithm, and make them interchangeable. Its purpose is to encapsulate each algorithm into an independent class with a common interface for a set of algorithms, so that they can be replaced with each other and the algorithm can change without affecting the client.

The user places an order - using the observer mode

The Observer Pattern is also called the publish-subscribe pattern. Its purpose is to define a one-to-many dependency relationship between objects, so that whenever an object changes state, all objects that depend on it will be notified and automatically renew.

Connecting to the database uses singleton mode

Permission Management-Agent Mode

The proxy mode accesses the target object through the proxy object, which can enhance additional functions based on the target object, such as adding permissions, access control and auditing functions.

What should you pay attention to when writing a singleton?

  1. The singleton mode ensures that there is only one object for this instance in the system memory, saving system resources. Using the singleton mode can improve system performance.
  2. When instantiating a singleton object, use the corresponding method to obtain the object instead of new.
  3. Scenarios for using the singleton pattern: objects that need to be created and destroyed frequently, objects that take too much time to create or consume too many resources (ie: heavyweight objects), but are frequently used, tool objects, frequently Objects that access databases or files (such as data sources, session factories, etc.)

Understanding the factory model

As the name suggests, the factory pattern is used to produce objects. In Java, everything is an object. There are many things that need to be created. If you create an object and use new, the object will be severely coupled to the object. If you need to replace the object, you must use Change everything in the object

If you use the factory pattern, you only need to make changes in the factory of the production object when replacing the object, which reduces object coupling.

Factory mode is divided into three modes:

(1) Simple factory mode, a factory method that returns the object to be generated based on the parameters passed in. This mode separates the created object from the application code, but cannot dynamically change the creation behavior. For example, a factory can To generate apple objects and orange objects, but later need to produce peach objects, the factory class must be modified, which has great limitations.

(2) **Factory method pattern extracts the factory into an abstract class or interface. The specific objects produced are determined by the subclasses. For example, the factory class that produces apples and oranges inherits the fruit factory abstract class, and the subclasses each produce their own objects, which requires Which factory class is called for whatever fruit is produced. **This mode has the same meaning as the simple factory mode. When you need to produce peach objects, you must create a peach factory to inherit the fruit factory, which still has great limitations.

(3) Abstract factory pattern. The abstract factory pattern can be used when there are many objects that need to be produced and there are dependencies . For example, now we need to produce four objects: apple juice, apple pie, banana juice, and banana pie. They can be divided into two categories: banana and apple. First create an abstract class to produce juice and pie, and then the apple factory inherits this abstract class and rewrites it. The two methods for producing juice and pie produce apple juice and apple pie. Similarly, the banana factory also inherits it to produce banana juice and banana pie, which reduces the coupling of objects.

Do you understand design patterns?

factory design pattern

Define an interface for creating objects and let subclasses decide which class to instantiate. The factory method pattern allows the instantiation of a class to be deferred to its subclasses. ( That is, when adding products on the client, you only need to add specific product categories and specific factory categories )

Spring uses the factory pattern to create bean objects through BeanFactoryor .ApplicationContext

Compare the two:

  • BeanFactory: Delayed injection (it will only be injected when a certain bean is used). Compared with , it ApplicationContextwill occupy less memory and the program will start faster.
  • ApplicationContext: When the container starts, regardless of whether you use it or not, all beans are created at once. BeanFactoryIt only provides the most basic dependency injection support. ApplicationContextAfter expansion BeanFactory, in addition to BeanFactorysome functions, there are additional functions, so most developers ApplicationContextwill use it more.

Singleton design pattern

There can only be one object instance for a class, and the class only provides one method (static method) to obtain its object instance.

The default scope of beans in Spring is singleton.

1. Construct private:

If I want to ensure that a class cannot be instantiated multiple times, then I must prevent the object from being new, so I need to privatize all constructors of the class.
2. Return the instance as a static method .

Because the outside world cannot obtain the object through new, we have to provide class methods to let the outside world obtain the object instance.

3. Make sure there is only one object instance .

The class is instantiated only once, and the object instantiated for the first time is directly obtained in the future.

Hungry mode

The hungry man mode means that I create the object (bread) first, and when I want to use it (eat it), I can just get it directly.

lazy mode

Because the hungry mode may cause a waste of resources, there is the lazy mode. The lazy mode means that I will not create an object instance of the class first, and I will create it when you need it.

Problems that lazy mode may cause in concurrent situations

The lazy mode solves the problem of resource waste that may be caused by the hungry mode, because this mode will only instantiate objects when the user wants to use them. However, this mode will create multiple objects in concurrent situations.

Because there may be multiple external people accessing the SingleCase.getInstance() method at the same time, there may be concurrency issues that cause the class to be instantiated multiple times , so the lazy mode needs to add a lock synchronized (Singleton.class) to control the class to only be instantiated. melt once.

//懒汉模式,双重null检查
class Singleton{
    private volatile static Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance() {
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
//饿汉模式
class Singleton2{
    private static final Singleton2 instance = new Singleton2();
    private Singleton2(){}

    public static Singleton2 getInstance() {
        return instance;
    }
}
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}
//静态内部类模式
public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE;  
    }  
}
//枚举
public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
}

proxy design pattern

Provides a stand-in for an object to control access to the object. That is, accessing the target object through the proxy object has the advantage that additional functional operations can be enhanced based on the implementation of the target object, that is, the functions of the target object can be expanded.

AOP (Aspect-Oriented Programming) can encapsulate logic or responsibilities (such as transaction processing, log management, permission control, etc.) that have nothing to do with the business but are commonly called by business modules to reduce duplicate code in the system. , reduce the coupling between modules and facilitate future scalability and maintainability .

strategy pattern

Strategy Pattern, also called policy pattern, is a relatively simple pattern. Its purpose is to define a set of algorithms, encapsulate each algorithm, and make them interchangeable. Its purpose is to encapsulate each algorithm into an independent class with a common interface for a set of algorithms, so that they can be replaced with each other and the algorithm can change without affecting the client.

template method pattern

The template method pattern defines the skeleton of an algorithm in operation and defers some steps to subclasses, allowing subclasses to redefine certain specific steps of an algorithm without changing the structure of the algorithm .

In Spring jdbcTemplate, hibernateTemplateclasses ending with Template that operate on the database use the template pattern.

Observer pattern

Observer pattern is an object behavior pattern. It represents a dependency relationship between objects. When an object changes, the objects on which the object depends will also react. Spring's event-driven model is a classic application of the observer pattern. The Spring event-driven model is very useful and can decouple our code in many scenarios. For example, every time we add a product, we need to update the product index. At this time, we can use the observer pattern to solve this problem.

adapter mode

Observer pattern

Observer pattern is an object behavior pattern. It represents a dependency relationship between objects. When an object changes, the objects on which the object depends will also react. Spring's event-driven model is a classic application of the observer pattern. The Spring event-driven model is very useful and can decouple our code in many scenarios. For example, every time we add a product, we need to update the product index. At this time, we can use the observer pattern to solve this problem.

adapter mode

The enhancement or notification (Advice) of pring AOP uses the adapter mode

Guess you like

Origin blog.csdn.net/qq_43167873/article/details/130481531