Springboot Episode 31: Springboot Data Collection

To get the records with the same ID in two tables in the database, and get the fields in the other table, you can use the JOIN operation in SQL. Here is an example showing how to get related records in two tables via JOIN:

Suppose there are two tables: table1and table2, they have the same ID field. You want to get table1the record in and get table2another field in .

SELECT t1.*, t2.fieldName
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id

We use JOINthe operation to concatenate table1and table2, and ONspecify their shared ID field in the clause. By SELECTlisting in the statement t1.*, we selected table1all the fields in . At the same time, we use the fields in t2.fieldNamethe selection . This way, the query results will contain related records from both tables.table2fieldName

The Spring Boot project is always running on the server

ohup means that the process will not be terminated even after logging out

nohup java -jar jar包名 >  日志文件输出路径  2>&1  &

like:

nohup java -jar brain-deep-learn-server-0.0.1-SNAPSHOT.jar > /home/admin/logs/brain-deep-learn-server-0.0.1-SNAPSHOT.out 2>&1 &
日志文件输出路径 :  /home/admin/logs/brain-deep-learn-server-0.0.1-SNAPSHOT.out

& indicates that the program is running in the background

View process:

ps -ef | grep jar包名

like:

ps -ef | grep brain-deep-learn-server-0.0.1-SNAPSHOT.jar
package com.br.file.config;
 
 
import java.io.File;
import javax.servlet.MultipartConfigElement;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MultipartConfig {
    @Value("${server.tomcat.basedir}")
    private  String tempDir;
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String location = tempDir;
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }
}

Knife4j is an enhanced solution integrating Swagger2 and OpenAPI3

  • Provide a cloud-native aggregated OpenAPI document solution based on K8S+Docker

  • Simplify the use and learning cost of Knife4j, one-click deployment & integration & use

/api/swagger-ui/index.html

<!--引入Knife4j的官方start包,该指南选择Spring Boot版本<3.0,开发者需要注意-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
    <version>4.0.0</version>
</dependency>

api/druid/index.html

cd /usr/local/kibana/config/

  1. Open browser: Open your browser and enter the address http://localhost:5601.

  2. Access the login page: After opening in the browser http://localhost:5601, it will jump to the Kibana login page.

  3. Enter username and password: Enter your username and password to log in. These credentials are usually set when Kibana is installed and configured. If you have not set a username and password, you can try to log in with the default credentials.

  4. Start using Kibana: After successfully logging in, you will enter the main interface of Kibana. From here, you can use Kibana's various features to analyze and visualize your data.

  5. Get the Enrollment Token: Copy the Enrollment Token from your terminal output. This Token is usually generated when configuring the Elastic Stack for security authentication and authorization.

  6. Visit the login page: Open the Elastic Stack login page in your browser. Typically, http://localhost:5601the Kibana login page can be accessed by visiting .

  7. Enter Enrollment Token: On the login page, select the "Enrollment Token" or "Configure Elastic" option. Then, paste the Enrollment Token you copied from the terminal into the corresponding input box.

  8. Log in to the Elastic Stack: After entering the Enrollment Token, click "Login" or "Continue" to log in.

  9. Start using the Elastic Stack: After a successful login, you will be taken to the main interface of the Elastic Stack (usually Kibana). From here, you can use the various features of the Elastic Stack for data analysis, search, and visualization.

brew services start redis

brew services stop redis

https://www.elastic.co/cn/downloads/elasticsearch

https://www.elastic.co/cn/downloads/kibana

bin/elasticsearch-create-enrollment-tokenThe command is used to create an Enrollment Token in the Elastic Stack. When executing this command, you need to specify the scope (scope), eg kibana.

Here are the steps to get Enrollment Token:

  1. Open Terminal: Opens a terminal or command line interface.

  2. Navigate to the Elasticsearch installation directory: Use cdthe command to navigate to the Elasticsearch installation directory. For example, if Elasticsearch is installed on /usr/share/elasticsearch, you can execute the following command:

    cd /usr/share/elasticsearch
  3. Run elasticsearch-create-enrollment-tokencommand: Execute the following command to create an Enrollment Token:

    bin/elasticsearch-create-enrollment-token --scope kibana

    This will generate an Enrollment Token and display it in the terminal output.

  4. Copy Enrollment Token: Copy the Enrollment Token displayed in the terminal. You can use the mouse to select Tokens and right-click to copy them, or manually select them and use the copy command.

An error occurs indicating that the configuration item needs to be set to [xpack.security.enrollment.enabled] must be set to 'true' to create an enrollment tokenbefore creating an Enrollment Token .[xpack.security.enrollment.enabled]true

To fix this, you can follow these steps:

  1. Open the Elasticsearch configuration file: Find and open the Elasticsearch configuration file elasticsearch.yml, which is usually located configin the folder of the Elasticsearch installation directory.

  2. Search [xpack.security.enrollment.enabled]configuration item: Search in the configuration file [xpack.security.enrollment.enabled]to ensure that the configuration item exists.

  3. Set [xpack.security.enrollment.enabled]to true: [xpack.security.enrollment.enabled]Set the value to true, that is, enable the Enrollment function. If this configuration item does not exist, please manually add the following lines to the configuration file:

    xpack.security.enrollment.enabled: true
  4. Save configuration file: Save the modification to the configuration file.

  5. Restart Elasticsearch: Restart Elasticsearch for configuration changes to take effect.

After completing the above steps, try to execute bin/elasticsearch-create-enrollment-token --scope kibanathe command again, and the Enrollment Token should be successfully created.

ps aux|grep elasticsearch

When a "Couldn't connect to cluster" error occurs, it usually means that the Elasticsearch client was unable to connect to the specified cluster. This could be due to one of the following reasons:

  1. Incorrect cluster address: Please make sure that the cluster address you provide is correct and can be accessed through the network. Check network connectivity, firewall settings, and host reachability.

  2. Cluster health status: If the cluster is in a red or yellow health status, there may be a problem preventing the cluster from working properly. Please check the health status of the Elasticsearch cluster and review the cluster's log files for more information.

  3. Security configuration issues: If your Elasticsearch cluster has security features enabled, such as authentication or SSL/TLS encryption, you need to ensure that the client's connection configuration matches the cluster's security settings. Verify that security configurations such as certificates, usernames, and passwords are correct.

  4. Network proxy issues: If your network environment uses a proxy server, make sure the client's connection configuration includes the correct proxy settings.

In order to resolve this issue, you can try the following steps:

  • Verify the cluster address: Make sure that the cluster address you are using is correct and can be accessed through the network. Try using curlor other tools to test the ports connected to Elasticsearch.

  • Check cluster health: Use Elasticsearch's cluster management API or command-line tools to check the health of your cluster. If the cluster state is not healthy, check the cluster's log files for more information and troubleshoot the problem.

  • Check security configuration: If your cluster has security features enabled, make sure the client's connection is configured correctly and has appropriate authentication credentials or certificates.

  • Confirm network proxy settings: If your network environment uses a proxy server, make sure that the client's connection configuration includes the correct proxy settings.

x86_64

@DataIt is an annotation provided by Lombok, which is used to automatically generate common methods of Java classes, including getter, setter, toString(), equals(), hashCode()and other methods.

Using @Dataannotations can simplify the writing of Java classes and avoid manually writing a lot of boilerplate code. When we add @Dataannotations to a class, Lombok will automatically generate related methods during the compilation phase.

Specifically, @Datathe annotation automatically generates the following methods for all non-static fields in the class:

  • Getter method: Generate a corresponding getter method for each field to obtain the value of the field.

  • Setter method: Generate a corresponding setter method for each field to set the value of the field.

  • equals()Method: Generate corresponding equals()methods according to the fields in the class, which are used to compare whether the contents of two objects are equal.

  • hashCode()Method: Generate the corresponding hashCode()method according to the field in the class, which is used to calculate the hash code of the object.

  • toString()Method: Generates a string representation of all fields in the class and their values.

Using @Dataannotations can greatly simplify code and improve development efficiency, especially for those POJO classes that contain a large number of fields.

For example, here is an @Dataexample using annotations:

@Data
public class Person {
    private String name;
    private int age;
    private String address;
}

In the above code, @Dataannotations are marked Personon the class, and Lombok will automatically generate methods such as getName(), setName(), getAge(), setAge(), getAddress(), setAddress(), equals(), hashCode()and .toString()

In short, @Datathe annotation is a convenient Lombok annotation, which is used to automatically generate common methods, reduce boilerplate code, and improve development efficiency.

In Spring Boot, BO(Business Object) is a common naming convention to denote a business object. BOUsually used to encapsulate business logic and data operations, representing concepts or entities in the business domain. The architect considers the following points when designing the architecture:

  1. Encapsulation of business logic : BOIt is used to encapsulate specific business logic, gather related codes of business processing together, and realize high cohesion of business logic. This helps in code organization and maintenance, and improves code readability and maintainability.

  2. Representation of domain model : BORepresents concepts or entities in the business domain. By BOdefining fields and methods in it, objects and their behaviors in the business domain can be better described and expressed. BOCan interact with database tables, external services, user input, etc., process and manipulate related data.

  3. Business rules and validation : BOBusiness rules and validation logic can be included to ensure the legality and consistency of business operations. By BOdefining the verification method in , you can verify the data and execute the corresponding processing logic before or after the business operation.

  4. Interaction with other layers : BOIt can be used as an intermediate object for business logic layer to interact with other layers (such as controller, service layer, persistence layer). BOIt can receive and transmit data, process and convert data, and coordinate and communicate with other layers to realize the overall function of the system.

By encapsulating business logic in BO, you can separate concerns and improve code maintainability and scalability. At the same time, BOthe design of the system should consider the rationality of the domain model and the change of business requirements in order to meet the evolution and expansion of the system.

<!--引入Knife4j的官方start包,该指南选择Spring Boot版本<3.0,开发者需要注意-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
    <version>4.0.0</version>
</dependency>
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "dockerBean")
    public Docket dockerBean() {
        //指定使用Swagger2规范
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                //描述字段支持Markdown语法
                .description("# Knife4j RESTful APIs")
                .termsOfServiceUrl("https://doc.xiaominfo.com/")
                .contact("[email protected]")
                .version("1.0")
                .build())
                //分组名称
                .groupName("用户服务")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.github.xiaoymin.knife4j.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
}
@Api(tags = "首页模块")
@RestController
public class IndexController {

    @ApiImplicitParam(name = "name",value = "姓名",required = true)
    @ApiOperation(value = "向客人问好")
    @GetMapping("/sayHi")
    public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){
        return ResponseEntity.ok("Hi:"+name);
    }
}

1440 means that the expiration time of the Token is 1440 minutes, that is, 24 hours. This setting is reasonable in most cases, because generally speaking, the user's login status should automatically expire after a certain period of time, requiring the user to log in again to ensure security.

Setting the expiration time of Token to 24 hours can provide certain user experience and security. After the user logs in, they can continue to use the app throughout the day without frequently re-logging in. At the same time, a short expiration time can reduce the risk of Token being stolen, because after the Token expires in a short period of time, hackers cannot continue to use the stolen Token to access the user's account.

However, the setting of the expiration time still needs to be adjusted according to specific application scenarios and security requirements. If your application has very high security requirements, you can consider shortening the expiration time of Token, such as setting it to a few hours or tens of minutes, which can further reduce the risk of being stolen. Conversely, if the application has high requirements for user convenience, the expiration time can be extended appropriately to provide a better user experience.

In general, the Token expiration time of 1440 minutes (that is, 24 hours) is reasonable under normal circumstances, but the specific setting needs to be determined according to the actual needs and security requirements of the application.

In the front-end application, the Token will be returned by the backend after the user logs in successfully, and saved in the front-end Cookie or LocalStorage. When the user makes other requests that require authentication, the front end will carry this Token for authentication. The following situations may cause the front-end Token to be lost or invalid, thus triggering the authentication failure handler:

  1. Token Expiration: The Token saved in the front end may have a validity period. If it exceeds the validity period, it will become invalid and the user needs to log in again to obtain a new Token.

  2. Token has been tampered with: If the Token is illegally tampered with during transmission, or the Token stored in the front-end is maliciously modified, the back-end will fail the verification and consider the Token invalid.

  3. Back-end service restart or Token re-generation: When the back-end service restarts, the original Token may become invalid, because the back-end will regenerate a new Token, requiring the user to log in again to obtain a new Token.

  4. Incorrect carrying of Token: When the front-end sends a request that requires authentication, it may forget to carry the Token in the request header or the format of the carried Token is incorrect, resulting in the failure of the back-end to verify the identity.

Regarding the code you provided, AuthenticationEntryPointImplthere doesn't seem to be an obvious error in the implementation of the class. Its function is to return a JSON response containing error information when authentication fails. If the Token carried by the front-end is invalid or expired, the back-end will return a 401 status code and a prompt message informing the user that the authentication failed and system resources cannot be accessed.

The possible cause of the error is that the Token carried by the front-end is invalid. You can check the request header in the front-end developer tools to ensure that the Token is correctly carried in the Authorization header or other appropriate locations. In addition, you can also check the logic of token generation in the backend to ensure that the token generation and verification process is correct.

Add the group to contact the author vx: xiaoda0423

Warehouse address: https://github.com/webVueBlog/JavaGuideInterview

Guess you like

Origin blog.csdn.net/qq_36232611/article/details/131874859