Taogen's Blog

Stay hungry stay foolish.

Logback is a popular logging framework for Java applications, designed as a successor to the well-known Apache Log4j framework. It’s known for its flexibility, performance, and configurability. Logback is extensively used in enterprise-level Java applications for logging events and messages.

In this post, I will cover various aspects of using Logback with Spring Boot.

Dependencies

Before we can use Logback in a Spring Boot application, we need to add its library dependencies to the project.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>{LATEST_VERSION}</version>
</dependency>

It contains ch.qos.logback:logback-classic and org.slf4j:slf4j-api

Logback Configuration Files

Spring Boot projects use logback-spring.xml or logback.xml in the resources directory as the Logback configuration file by default.

Priority of the Logback default configuration file: logback.xml > logback-spring.xml.

If you want to use a custom filename. You can specify the log configuration file path in application.xml or application.yml. For example:

logging:
config: classpath:my-logback.xml

Logback Basic Configurations

Property

You can define some properties that can be referenced in strings. Common properties: log message pattern, log file path, etc.

<configuration>
<property name="console.log.pattern"
value="%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}:%line%n) - %msg%n"/>
<property name="file.log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"/>
<property name="file.log.dir" value="./logs"/>
<property name="file.log.filename" value="mylogs"/>

</configuration>

Appender

Appenders define the destination and formatting (optional) for log messages.

Types of Logback Appenders:

  • ConsoleAppender: Writes log messages to the console window (standard output or error).
  • FileAppender: Writes log messages to a specified file.
  • RollingFileAppender: Similar to FileAppender, but it creates new log files based on size or time intervals, preventing a single file from growing too large.
  • SocketAppender: Sends log messages over a network socket to a remote logging server.
  • SMTPAppender: Sends log messages as email notifications.

ConsoleAppender

<configuration>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${console.log.pattern}</pattern>
<charset>utf8</charset>
</encoder>
</appender>

</configuration>

FileAppender

<configuration>

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${file.log.dir}/${file.log.filename}.log</file>
<encoder>
<pattern>${file.log.pattern}</pattern>
</encoder>
</appender>

</configuration>

RollingFileAppender

<configuration>

<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${file.log.dir}/${file.log.filename}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- Log file will roll over daily -->
<fileNamePattern>${file.log.pathPattern}</fileNamePattern>
<!-- Keep 30 days' worth of logs -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Log messages greater than or equal to the level -->
<level>INFO</level>
</filter>
<encoder>
<pattern>${file.log.pattern}</pattern>
</encoder>
</appender>

</configuration>

RollingPolicy

A rollingPolicy is a component attached to specific appenders that dictates how and when log files are automatically managed, primarily focusing on file size and archiving. Its primary function is to prevent log files from becoming excessively large, improving manageability and performance.

Purpose:

  • Prevents large log files: By periodically rolling over (rotating) log files, you avoid single files growing too large, which can be cumbersome to manage and slow down access.
  • Archiving logs: Rolling policies can archive rolled-over log files, allowing you to retain historical logs for analysis or auditing purposes.

Functionality:

  • Triggers rollover: Based on the defined policy, the rollingPolicy determines when to create a new log file and potentially archive the existing one. Common triggers include exceeding a certain file size or reaching a specific time interval (e.g., daily, weekly).
  • Defines archive format: The policy can specify how archived log files are named and organized. This helps maintain a clear structure for historical logs.

Benefits of using rollingPolicy:

  • Manageability: Keeps log files at a manageable size, making them easier to handle and access.
  • Performance: Prevents performance issues associated with excessively large files.
  • Archiving: Allows you to retain historical logs for later use.

Common types of rollingPolicy in Logback:

  • SizeBasedTriggeringPolicy: Rolls over the log file when it reaches a specific size limit (e.g., 10 MB).
  • TimeBasedRollingPolicy: Rolls over the log file based on a time interval (e.g., daily, weekly, monthly).
  • SizeAndTimeBasedRollingPolicy: Combines size and time-based triggers, offering more control over rolling behavior.

TimeBasedRollingPolicy

<configuration>
<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
...
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- Log file will roll over daily -->
<fileNamePattern>${file.log.dir}/${file.log.filename}-%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Keep 30 days' worth of logs -->
<maxHistory>30</maxHistory>
</rollingPolicy>
...
</appender>
</configuration>

SizeAndTimeBasedRollingPolicy

<configuration>
<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
...
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${file.log.dir}/${file.log.filename}-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<!-- each archived file's size will be max 10MB -->
<maxFileSize>10MB</maxFileSize>
<!-- 30 days to keep -->
<maxHistory>30</maxHistory>
<!-- total size of all archive files, if total size > 100GB, it will delete old archived file -->
<totalSizeCap>100GB</totalSizeCap>
</rollingPolicy>
...
</appender>
</configuration>

Filter

A filter attached to an appender allows you to control which log events are ultimately written to the defined destination (file, console, etc.) by the appender.

Commonly used filters:

  • ThresholdFilter: This filter allows log events whose level is greater than or equal to the specified level to pass through. For example, if you set the threshold to INFO, then only log events with level INFO, WARN, ERROR, and FATAL will pass through.
  • LevelFilter: Similar to ThresholdFilter, but it allows more fine-grained control. You can specify both the level to match and whether to accept or deny log events at that level.

Filter only INFO level log messages.

<configuration>
<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
...
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
...
</appender>
</configuration>

Filter level greater than INFO

<configuration>
<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
...
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
...
</appender>
</configuration>

Logger

A logger in logback.xml represents a category or source for log messages within your application.

There are two types of logger tags in Logback: <root> and <logger>. They have hierarchical relationships. All <logger> are <root> child logger. Loggers can inherit their parent logger’s configurations. <root> represents the top level in the logger hierarchy which receives all package log messages. <logger> receives log messages from a specified package.

<configuration>

<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</root>

<logger name="com.taogen" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</logger>

</configuration>
  • <root>: It receive all package log messages.
    • level="INFO": define the default logger level to INFO for all loggers.
    • <appender-ref>: Send messages to CONSOLE and ROLLING_FILE appender.
  • <logger>
    • name="com.taogen: It receive the com.taogen package log messages.
    • level="DEBUG": It overrides the logger level to DEBUG.
    • additivity="false": If the message has been sent to a appender by its parent logger, current logger will not send the message to the same appender again.
    • <appender-ref>: Send message to CONSOLE and ROLLING_FILE appender.

Using Logback

package com.taogen.commons.boot.mybatisplus;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@SpringBootTest(classes = AppTest.class)
@ExtendWith(SpringExtension.class)
@Slf4j
class LogTest {
private static Logger logger = LoggerFactory.getLogger(LogTest.class);

private static Logger customLogger = LoggerFactory.getLogger("my-custom-log");

@Test
void test1() {
log.debug("This is a debug message");
log.info("This is an info message");
log.warn("This is a warn message");
log.error("This is an error message");

logger.debug("This is a debug message");

customLogger.debug("This is a debug message");
customLogger.info("This is an info message");
customLogger.warn("This is a warn message");
customLogger.error("This is an error message");
}
}

@Slf4j is a Lombok annotation that automatically creates a private static final field named log of type org.slf4j.Logger. This log field is initialized with an instance of the SLF4J logger for the current class.

private static Logger log = LoggerFactory.getLogger(LogTest.class);

The commonly used Logback levels (in order of increasing severity):

  • TRACE: Captures the most detailed information.
  • DEBUG: general application events and progress.
  • INFO: general application events and progress.
  • WARN: potential problems that might not cause immediate failures.
  • ERROR: errors that prevent the program from functioning correctly.

Relationships between Logger object and <logger> in logback.xml

  • <logging> defined in logback.xml usually uses a package path as its name. Otherwise, use a custom name.
  • If you use Logback to print log messages in Java code, first, you need to pass a class or string to LoggerFactory.getLogger() method to get a Logger object, then call logger’s methods, such as debug().
  • If the Logger object is obtained through a class, Logback looks for <logger> from logback.xml using the object’s package or parent package path. If the Logger object is obtained through a string, Logback uses the string to find a custom <logger> from logback.xml.

More Configurations

Custom Loggers

You can create a custom logger by setting a name instead of using a package path as its name.

<configuration>

<logger name="my-custom-log" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE_CUSTOM"/>
</logger>

</configuration>

Output log messages:

2024-03-07 09:20:43 [main] INFO  my-custom-log - Hello!
2024-03-07 09:21:57 [main] INFO my-custom-log - Hello!
  • my-custom-log: logger name.

Note that if you use a custom logger, you can’t get class information from the log message.

Configurations for Different Environments

Using <springProfile>

<configuration>
...
. <!-- springProfile: 1) name="dev | test". 2) name="!prod" -->
<springProfile name="dev | test">
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</root>
<logger name="com.taogen.commons" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</logger>
</springProfile>
<springProfile name="prod">
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</root>
</springProfile>
</configuration>

Dynamically set the log configuration file path

You can dynamically set the log configuration file path in application.yml. Different spring boot environments use different log configuration files.

application.yml

logging:
config: classpath:logback-${spring.profiles.active}.xml

logback-dev.xml

<configuration>
...
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</root>
<logger name="com.taogen.commons" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</logger>
</configuration>

logback-prod.xml

<configuration>
...
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE"/>
</root>
</configuration>

A Complete Example

Goals

  • Properties
    • log patterns, log directory and log filename.
  • Appenders
    • Colorful log pattern for console appender.
    • Console and RollingFile appenders.
    • Time based rolling policy. Roll over daily, Keep 30 days’ worth of logs.
    • Filter log messages in appenders. Separate INFO, ERROR log messages.
  • Loggers
    • Setting loggers of the root and the base package of project.
    • Using custom loggers.
    • Support multiple spring boot environments.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration>
<!-- Define properties. You can use these properties in appender configurations.-->
<property name="console.log.pattern"
value="%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}:%line%n) - %msg%n"/>
<property name="file.log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"/>
<property name="file.log.dir" value="./logs"/>
<property name="file.log.filename" value="mylogs"/>

<!-- Define the CONSOLE appender. 1) log pattern. 2) log file path. -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${console.log.pattern}</pattern>
<charset>utf8</charset>
</encoder>
</appender>

<!-- RollingFileAppender: Adds the capability to perform log file rotation. You can define a rolling policy, specifying criteria such as time-based or size-based rollover. -->
<appender name="ROLLING_FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${file.log.dir}/${file.log.filename}-info.log</file>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- Log file will roll over daily -->
<fileNamePattern>${file.log.dir}/${file.log.filename}-info-%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Keep 30 days' worth of logs -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${file.log.pattern}</pattern>
</encoder>
</appender>

<appender name="ROLLING_FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${file.log.dir}/${file.log.filename}-error.log</file>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- Log file will roll over daily -->
<fileNamePattern>${file.log.dir}/${file.log.filename}-error-%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Keep 30 days' worth of logs -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${file.log.pattern}</pattern>
</encoder>
</appender>

<appender name="ROLLING_FILE_CUSTOM" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${file.log.dir}/custom-logs.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- Log file will roll over daily -->
<fileNamePattern>${file.log.dir}/custom-logs-%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Keep 30 days' worth of logs -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${file.log.pattern}</pattern>
</encoder>
</appender>

<!-- Define root logger. 1) Set the default level for all loggers. 2) Set which appenders to use. -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE_INFO"/>
<appender-ref ref="ROLLING_FILE_ERROR"/>
</root>
<!-- custom logger -->
<logger name="my-custom-log" level="INFO" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE_CUSTOM"/>
</logger>
<!-- springProfile: 1) name="dev | test". 2) name="!prod" -->
<springProfile name="dev | test">
<!-- Define loggers. Set log level for specific packages. -->
<logger name="com.taogen.commons" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ROLLING_FILE_INFO"/>
<appender-ref ref="ROLLING_FILE_ERROR"/>
</logger>
</springProfile>
</configuration>

Principles

  • Oriented toward novices. It is assumed that most of the readers of the document are novices. This way you will write more understandable, in-depth, detailed, and readable.

Structure

  • Overall logic: what, why, how, when, where.
  • Try to break out into detailed subdirectories. You can quickly locate what you want to see.

Details

  • The steps should be clear. Label steps 1, 2, and 3.
  • Try to add links to nouns that you can give links to. E.g. official website, explanation of specialized terms.
  • The code field is to be marked with a code, e.g. code.
  • Use tables as much as possible for structured information.
  • Try to use pictures where you can illustrate to make a clearer and more visual illustration. Don’t mind the hassle. It is more visual and easier to read. For example: UML, flow chart.
  • Give a link to the reference content at the end.

Others

  • After writing, read it through at least once. Timely detection and revision of some statement errors, incoherence; inaccuracy and lack of clarity of expression, and so on.

Write Statistical SQLs

Before write the code, you can write statistical SQLs first. Because the core of statistical APIs are SQLs. As the saying goes, “first, solve the problem, then, write the code”.

Define Parameter and Response VOs

VO (value object) is typically used for data transfer between business layers and only contains data.

Parameter VOs

@Data
public class SomeStatParam {
private Date beginTime;
private Date endTime;
private Integer type;
private Integer userId;
...
}

Response VOs

@Data
public class someStatResult {
...
}

Write the APIs

@RestController
@RequestMapping(value = "/moduleName")
public class SomeStatController {
@GetMapping(value = "/getSomeStat")
public ResponseEntity<SomeStatResult> getSomeStat(SomeStatParam someStatParam) {
SomeStatResult data = someStatService.getSomeStat(someStatParam);
return ResponseEntity.ok(data);
}
}

Test APIs in Your Local Environment

Before integrating third-party APIs in your web application, it’s better to test the APIs with an API tool like Postman to ensure the APIs work properly in your local environment. It can also let you get familiar with the APIs.

Add API Configurations to Your Project

There are some common configurations of third-party APIs you need to add to your project. For example, authorization information (appId, appSecret), API URL prefix, and so on.

Add Configurations

Add the configurations to your spring boot configuration file application.yaml:

thirdParty:
thirdParty1:
appId:
appSecret:
apiBaseUrl:
thirdParty2:
...

Define the Configuration Bean

Add a spring bean to receive the configurations:

YourThirdPartyConfig.java

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "thirdParty.yourThirdPartyName")
@Data
public class YourThirdPartyConfig {
protected String appId;
protected String appSecret;
protected String apiBaseUrl;
}

You can access the configurations by @Autowired it

@Autowired
private YourThirdPartyConfig yourThirdPartyConfig;
String appId = yourThirdPartyConfig.appId;
String appSecret = yourThirdPartyConfig.appSecret;
String apiBaseUrl = yourThirdPartyConfig.apiBaseUrl;

Define Response Code

public class YourThirdPartyErrorCode {  
public static final Integer SUCCESS = 0;
public static final Integer INVALID_APPID = 1;
public static final Integer INVALID_TOKEN = 2;
}

Define API URLs

public class YourThirdPartyApiUrl {
public static class Module1 {
public static final String xxx_URL = "";
}

public static class Module2 {
public static final String xxx_URL = "";
}
}

Define Base Service

@RequiredArgsConstructor
public abstract class YourThirdPartyBaseService {
protected final YourThirdPartyConfig yourThirdPartyConfig;

private final RestTemplate restTemplate;

public ObjectNode getRequest(String url, MultiValueMap params) throws IOException {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(
yourThirdPartyConfig.apiBaseUrl + url)
.queryParams(params);
ResponseEntity<String> response = restTemplate.getForEntity(uriBuilder.toUriString(), String.class);
if (response.getStatusCode().is2xxSuccessful()) {
ObjectNode jsonObject = JacksonJsonUtil.jsonStrToJsonObject(response.getBody());
if (YourThirdPartyErrorCode.SUCCESS.equals(jsonObject.get("code").asInt())) {
return jsonObject;
} else {
throw new RuntimeException("Failed to get access token: " + jsonObject.get("message").asText());
}
} else {
throw new RuntimeException("Failed to get access token: HTTP error code " + response.getStatusCodeValue());
}
}
}

Get and Cache Access Token

@Service
@Slf4j
@RequiredArgsConstructor
public class YourThirdPartyTokenService extends YourThirdPartyBaseService {
public static final String KEY_ACCESS_TOKEN = "yourThirdParty:%s:access_token";
private final YourThirdPartyConfig yourThirdPartyConfig;
private final RestTemplate restTemplate;
private final RedisUtil redisUtil;

public String getAccessToken() throws IOException {
return getAccessToken(yourThirdPartyConfig.appId, yourThirdPartyConfig.appSecret);
}

public String getAccessToken(String appId, String appSecret) throws IOException {
String accessToken = getAccessTokenFromCache(appId);
if (StringUtils.isNotBlank(accessToken)) {
log.debug("get access_token from redis: {}", accessToken);
return accessToken;
}
log.debug("get access_token from API");
ObjectNode jsonObject = getTokenInfoFromApi(appId, appSecret);
setTokenToCache(jsonObject, appId);
return jsonObject.get("accessToken").asText();
}

private String getAccessTokenFromCache(String appId) {
return redisUtil.get(String.format(KEY_ACCESS_TOKEN, appId), 0);
}

private void setTokenToCache(ObjectNode jsonObject, String appId) {
String accessToken = jsonObject.get("result").get("accessToken").asText();
Integer expiresIn = jsonObject.get("result").get("expires").asInt();
redisUtil.set(String.format(KEY_ACCESS_TOKEN, appId), accessToken, 0, "nx", "ex", expiresIn - 60);
}


public ObjectNode getTokenInfoFromApi(String appId, String appSecret) throws IOException {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("appId", Arrays.asList(apiKey));
params.put("appSecret", Arrays.asList(secretKey));
return super.getRequest(YourThirdPartyApiUrl.Token.GET_ACCESS_TOKEN_URL, params);
}
}

Write Code

Define the API Interfaces

Here we use the example of the social login API service to demonstrate.

public interface SocialLoginService {
JSONObject func1(JSONObject params);
JSONObject func2(JSONObject params);
// More functions...
}

Why use JSONObject as parameters and return types of methods of the interface?

Different third-party API service platforms have different data structures. The parameters and return types of methods need to be extensible.

Define Constants

Keys for API parameters

public class Auth0Key {
public static final String CODE = "code";
public static final String MSG = "msg";
public static final String USER_NAME = "user_name";
}

API request URIs

public class Auth0Url {
public static final String LOGIN = "/login";
public static final String GET_USER_INFO = "/user/getInfo";
// More URLs ...
}

Write the API Implementing Class

@Service
public class Auth0SocialLoginService implements SocialLoginService {
@Autowired
private Auth0Config auth0Config;

public JSONObject func1(JSONObject params) {
...
}
public JSONObject func2(JSONObject params) {
...
}
}

Common third-party APIs and their class names

API Service Interface Name Implementation Name
Cloud Object Storage COSService AwsCOSService
AzureCOSService
Push Notification APIs PushNotificationService OneSignalPushService
Social Media Login APIs SocialLoginService Auth0SocialLoginService
FirebaseSocialLoginService

Write Parameter Builders and Result Handlers

Parameter builders

public interface SocialLoginParamBuilder {
JSONObject getFunc1Param(Xxx entity);
JSONObject getFunc2Param(Xxx entity);
}
@Component
public class Auth0SocialLoginParamBuilder implements SocialLoginParamBuilder {
JSONObject getFunc1Param(Xxx entity) {...}
JSONObject getFunc2Param(Xxx entity) {...}
}

Result handlers

public interface SocialLoginResultHandler {
Vo handleFunc1Result(JSONObject result);
Vo handleFunc2Result(JSONObject result);
}
@Component
public class Auth0SocialLoginResultHandler implements SocialLoginResultHandler {
Vo handleFunc1Result(JSONObject result) {...}
Vo handleFunc2Result(JSONObject result) {...}
}

Use Your Interface

@Autowired
@Qualifier("auth0SocialLoginService")
private SocialLoginService socialLoginService;
// or
@Autowired
private SocialLoginService auth0SocialLoginService; // The SocialLoginService object name must same as the implementing class name and the first character should be lowercase.

@Autowired
@Qualifier("auth0SocialLoginParamBuilder")
private SocialLoginParamBuilder socialLoginParamBuilder;

@Autowired
@Qualifier("auth0SocialLoginResultHandler")
private SocialLoginResultHandler socialLoginResultHandler;
JSONObject params = auth0SocialLoginParamBuilder.getFunc1Param(entity);
JSONObject result = auth0SocialLoginService.func1(params);
Vo vo = auth0SocialLoginResultHandler.handleFunc1Result(result);

This post will cover how to create a static website using VitePress.

Before using VitePress you must install Node.js v18 or higher.

Initialize VitePress Project

Add vitepress dependency

$ mkdir my-site
$ cd my-site

# add vitepress to devDependencies
$ npm add -D vitepress
# or
$ yarn add -D vitepress

VitePress is used in the development process as a build tool. It converts your Markdown files to HTML files. You don’t need VitePress in runtime.

Scaffold a basic project

$ npx vitepress init

npx can run your installed package directly, you don’t need to add any npm script to your package.json. You also can do npx package_command by using npm run your_script.

You need to set some basic configuration for your website.

  • Setting the VitePress directory. ./ means using the root directory.
  • Setting your site title.
  • Setting your site description.
  • Other configurations just use the default settings.
┌  Welcome to VitePress!

◇ Where should VitePress initialize the config?
│ ./

◇ Site title:
│ My Awesome Project

◇ Site description:
│ A VitePress Site

◇ Theme:
│ Default Theme

◇ Use TypeScript for config and theme files?
│ Yes

◇ Add VitePress npm scripts to package.json?
│ Yes

└ Done! Now run npm run docs:dev and start writing.

Running the project

Start a local server

npm run docs:dev
# or
yarn docs:dev
# or
npx vitepress dev

Visiting http://localhost:5173 to access the website

Git Configurations

Initialize the git repository

$ cd my-site
$ git init .

Config gitignore

Add the .vitepress/cache directory to .gitignore

.vitepress/cache

Result .gitignore

.idea

# macOS
.DS_Store

# vitepress
.vitepress/cache

# Dependency directories
node_modules/

# build output
dist

VitePress Configurations

Site Config

The site configuration file is .vitepress/config.mts

export default defineConfig({
title: '{my_title}',
description: '{my_description}',
srcDir: 'src',
srcExclude: [
'someDir/**',
'someFile',
],
// Whether to get the last updated timestamp for each page using Git.
lastUpdated: true,
head: [
['link', {rel: 'shortcut icon', type: "image/jpeg", href: '/logo.jpeg'}],
// These two are what you want to use by default
['link', {rel: 'apple-touch-icon', type: "image/jpeg", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon', type: "image/jpeg", sizes: "72x72", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon', type: "image/jpeg", sizes: "114x114", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon', type: "image/jpeg", sizes: "144x144", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon-precomposed', type: "image/jpeg", href: '/logo.jpeg'}],
// This one works for anything below iOS 4.2
['link', {rel: 'apple-touch-icon-precomposed apple-touch-icon', type: "image/jpeg", href: '/logo.jpeg'}],
],
themeConfig: {
//...
}
})
$ mkdir src/ && mv index.md src/

Files

  • src/public/logo.jepg

srcDir

Move the home page index.md to src/index.md

$ mkdir src/
$ mv index.md src/
export default defineConfig({

srcDir: 'src',

})

srcExclude

Optional config. If you need to add excluded directories and files.

export default defineConfig({

srcExclude: [
'someDir/**',
'someFile',
],

})

For example:

  • docs/**,
  • index-en.md

lastUpdated

export default defineConfig({

// Whether to get the last updated timestamp for each page using Git.
lastUpdated: true,

})

Shortcut icon

export default defineConfig({

head: [
['link', {rel: 'shortcut icon', type: "image/jpeg", href: '/logo.jpeg'}],
// These two are what you want to use by default
['link', {rel: 'apple-touch-icon', type: "image/jpeg", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon', type: "image/jpeg", sizes: "72x72", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon', type: "image/jpeg", sizes: "114x114", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon', type: "image/jpeg", sizes: "144x144", href: '/logo.jpeg'}],
['link', {rel: 'apple-touch-icon-precomposed', type: "image/jpeg", href: '/logo.jpeg'}],
// This one works for anything below iOS 4.2
['link', {rel: 'apple-touch-icon-precomposed apple-touch-icon', type: "image/jpeg", href: '/logo.jpeg'}],
],

})

src/public/logo.jepg

Theme Config

The theme configuration file is also .vietpress/config.mts

import {type DefaultTheme, defineConfig} from 'vitepress'

export default defineConfig({
themeConfig: {
nav: nav(),
sidebar: {
'/example/': sidebarExample()
},

logo: {src: '/your-logo.png', width: 24, height: 24},
search: {
provider: 'local'
},
outline: {
level: "deep"
},
}
})

function nav(): DefaultTheme.NavItem[] {
return [
{text: 'Home', link: '/'},
{text: 'Example', link: '/example/'},
];
}

function sidebarExample(): DefaultTheme.SidebarItem[] {
return [
{text: 'Examples', link: '/examples.md'},
]
}

Files

  • src/public/your-logo.png
export default defineConfig({
themeConfig: {

logo: {src: '/your-logo.png', width: 24, height: 24},

}
})

src/public/your-logo.png

export default defineConfig({
themeConfig: {

search: {
provider: 'local'
},

}
})

Outline

export default defineConfig({
themeConfig: {

outline: {
level: "deep"
},

}
})

Home Page Config

Config home page in src/index.md

Image

hero:
image:
src: your-home-image.png
alt: your-home-image

src/public/your-home-image.png

Feature Icons

features:
- icon: 🚀
title:
details:

Other Config

Favicon

Put your website icon to src/public/favicon.ico

Deployment

Create a repository on GitHub

Create button on the right top bar of GitHub -> New repository

Enter your repository name. For example, my-site

Click the “Create Repository” button.

Commit your local repository to GitHub

git add .
git commit -m '🎉feat: First commit'
git remote add origin git@github.com:{your_username}/{repo_name}.git
git branch -M main
git push -u origin main

Deploy your project on Vercel

Go to Vercel website.

Click the “Add New” button -> Project -> Import Git Repository

Add permission to access the new GitHub repository to Vercel

After finishing the permission configuration, you can find the new GitHub repository on Vercel.

Select the repository. And click “Import”

Override “Build and Output Settings”

  • Build Command: npm run docs:build or yarn docs:build
  • Output Directory: .vitepress/dist

Click “Deploy”

After the deployment process is finished, you can visit your website by Vercel provided URL.

Common text processing commands on Linux

  • grep
  • sed
  • awk
  • tr
  • sort
  • wc

Filter

Filter lines

echo -e "Foo\nBar" | grep "Fo"

Insert

Insert lines

Insert to the specific line

echo -e 'Foo\nBar' | sed '2i\the new line\' # Foo\nthe new line\nBar

Add line to beginning and end

echo -e 'Foo\nBar' | sed '1 i\First line'
echo -e 'Foo\nBar' | sed '$aEnd line'

Insert lines after match pattern

echo -e 'Foo\nBar' | sed '/Foo/a NewLine1\nNewLine2'
echo -e 'Foo\nBar' | sed '/Foo/r add.txt'

Insert text to the beginning and end

Insert text to the beginning of each line

echo 'foo' | sed 's/^/BeginText/'

Insert text to the end of each line

echo 'foo' | sed 's/$/EndText/'

Insert text to the begining and end of each line

echo 'foo' | sed 's/^/BeginText/' | sed 's/$/EndText/'

Insert a new line to the end of each line

echo -e 'Foo\nBar'| sed 's/$/\r\n/'

Replace

Replace first

echo "old names, old books" | sed 's/old/new/'
# or
echo "old names, old books" | sed '0,/old/{s/old/new/}'

Replace all

echo "old names, old books" | sed 's/old/new/g'

Remove

Remove matched lines

echo -e "Foo\nBar" | sed '/Foo/d'

Remove empty line

echo -e "Foo\n \nBar" | sed '/^\s*$/d'
# or
echo -e "Foo\n \nBar" | sed '/^[[:space:]]*$/d'

Remove comment /**/ or //

# reomve lines start with / or *
sed '/^ *[*/]/d'

Remove n lines after a pattern

# including the line with the pattern
echo -e "Line1\nLine2\nLine3\nLine4" | sed '/Line1/,+2d' # Line4

# excluding the line with the pattern
echo -e "Line1\nLine2\nLine3\nLine4" | sed '/Line1/{n;N;d}' # Line1\nLine4

Remove all lines between two patterns

# including the line with the pattern
sed '/pattern1/,/pattern2/d;'
echo -e "Foo\nAAA\nBBB\nBar\nCCC" | sed '/Foo/,/Bar/d' # CCC

# excluding the line with the pattern
sed '/pattern1/,/pattern2/{//!d;};'
echo -e "Foo\nAAA\nBBB\nBar\nCCC" | sed '/Foo/,/Bar/{//!d;}' # Foo\nBar\nCCC

Substring

Get substring by index

cut -c start-end1,start_end2
printf 'hello,world' | cut -c 1-5 # hello

Split and get fields

cut -d DELIMITER -f field_number1,field_number2
print 'hello,world' | cut -d ',' -f 2 # world

Find String

Find String by Pattern

echo -e 'Hello Java developer!\nHello Web developer!' | sed 's/Hello \(.*\) developer!/\1/'

Join

Join lines

echo -e "Foo\nBar" | tr '\n' ' '

Split

Split to multiple lines

echo "Foo Bar" | tr '[:space:]' '[\n*]'

Deduplication

# sort and deduplication
echo -e "1\n3\n2\n1" | sort -u

Sort

echo -e "1\n3\n2\n1" | sort

Count

Count lines

echo -e "1\n3\n2\n1" | wc -l # 4

Count matched lines

echo -e "1\n3\n2\n1" | grep -c "1" # 2

Count matched number of string

echo "hello world" | grep -o -i "o" | wc -l # 2

Format

To Upper/Lower Case

# to upper case
echo "hello WORLD" | tr a-z A-Z
# to lower case
echo "hello WORLD" | tr A-Z a-z

Format JSON string

echo '{"name":"Jack","age":18}' | jq .
echo '{"name":"Jack","age":18}' | jq .name

Crypto

Encode

Base64

Base64 Encode

printf 'hello' | base64
# or
echo -n 'hello' | base64
  • -n: do not output the trailing newline

Base64 Decode

printf 'hello' | base64 | base64 -d

URL encode

URL encode

printf '你好' | jq -sRr @uri
# or
echo -n '你好' | jq -sRr @uri
  • -n: do not output the trailing newline

Hash

md5

md5 -r /path/to/file
printf 'hello' | md5sum

echo -n 'hello' | md5sum
# or
echo -n 'hello' | md5
  • -n: do not output the trailing newline

md5sum on linux, md5 on macOS

sha

shasum -a 256 /path/to/file
printf 'hello' | shasum -a 256

Examples

Wrap in double quotes and join with comma

echo 'hello
world' | sed 's/^/"/' | sed 's/$/"/' | tr '\n' ','

SSH, or secure shell, is an encrypted protocol used to manage and communicate with servers. You can connect to your server via SSH. There are a few different ways to login an SSH server. Public key authentication is one of the SSH authentication methods. It allows you to access a server via SSH without a password.

Creating SSH keys

List supported algorithms of SSH keys on your client and server:

$ ssh -Q key

Output

ssh-ed25519
ssh-ed25519-cert-v01@openssh.com
ssh-rsa
ssh-dss
ecdsa-sha2-nistp256
ecdsa-sha2-nistp384
ecdsa-sha2-nistp521
ssh-rsa-cert-v01@openssh.com
ssh-dss-cert-v01@openssh.com
ecdsa-sha2-nistp256-cert-v01@openssh.com
ecdsa-sha2-nistp384-cert-v01@openssh.com
ecdsa-sha2-nistp521-cert-v01@openssh.com

Choose an algorithm that supports both your client and server for generating an SSH key pair.

$ ssh-keygen -t {your_algorithm} -C "{your_comment}"

We recommend using the ed25519 algorithm to generate your SSH key. The Ed25519 was introduced on OpenSSH version 6.5. It’s using elliptic curve cryptography that offers better security with faster performance compared to DSA, ECDSA, or RSA. The RSA is even considered not safe if it’s generated with a key smaller than 2048-bit length.

$ ssh-keygen -t ed25519 -C "mac_taogenjia@gmail.com"

Output

Enter file in which to save the key (/Users/taogen/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in {filename}
Your public key has been saved in {filename}.pub

You can specify your SSH key’s filename. If you don’t want to change the filename, by default the private key filename is id_{algorithm} and the public key filename is id_{algorithm}.pub .

For security reasons, it’s best to set a passphrase for your SSH keys.

Coping the SSH public key to your server

Copying Your Public Key Using ssh-copy-id

The simplest way to copy your public key to an existing server is to use a utility called ssh-copy-id.

ssh-copy-id -i public_key_filepath username@remote_host
# or use a specific SSH port
ssh-copy-id -i public_key_filepath -p ssh_port username@remote_host

For example

ssh-copy-id -i ~/.ssh/id_ed25519_remote_1.pub -p 38157 root@xxx.xx.xxx.xxx

Copying Your public key using SSH

cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
  • cat ~/.ssh/id_rsa.pub: Output the file.
  • mkdir -p ~/.ssh: Creating the ~/.ssh directory if it doesn’t exist.
  • cat >> ~/.ssh/authorized_keys: append the standard output of the previous command of the pipeline to the file ~/.ssh/authorized_keys on the remote host.

Configuring SSH

If there are multiple SSH keys on your local system, you need to configure which destination server uses which SSH key. For example, there is an SSH key for GitHub and another SSH key for a remote server.

Creating the SSH configuration file ~/.ssh/config if it doesn’t exist.

vim ~/.ssh/config

Add the config like the folowing content

# GitHub
Host github.com
User git
Port 22
Hostname github.com
IdentityFile "~/.ssh/{your_private_key}"
TCPKeepAlive yes
IdentitiesOnly yes

# Remote server
Host {remote_server_ip_address}
User {username_for_ssh}
Port {remote_server_ssh_port}
IdentityFile "~/.ssh/{your_private_key}"
TCPKeepAlive yes
IdentitiesOnly yes

SSH login with the SSH private key

If you have copied your SSH public key to the server, SSH login will automatically use your private key. Otherwise, you will need to enter the password of the remote server’s user to login.

$ ssh username@remote_host
# or use a specific port
$ ssh -p ssh_port username@remote_host

Disabling password authentication on your server

Using password-based authentication exposes your server to brute-force attacks. You can disable password authentication by updating the configuration file /etc/ssh/sshd_config.

Before disabling password authentication, make sure that you either have SSH key-based authentication configured for the root account on this server, or preferably, that you have SSH key-based authentication configured for an account on this server with sudo access.

sudo vim /etc/ssh/sshd_config

Uncomment the following line by removing # at the beginning of the line:

PasswordAuthentication no

Save and close the file when you are finished. To actually implement the changes we just made, you must restart the service.

sudo systemctl restart ssh

References

[1] How To Configure SSH Key-Based Authentication on a Linux Server

[2] Upgrade Your SSH Key to Ed25519

Configuring DNS

Ensure your Linux server’s DNS configuration file /etc/resolv.conf contains some DNS servers.

If there are no DNS servers in the /etc/resolv.conf, you must add some DNS servers to the file.

vim /etc/resolv.conf

Add the following content to the file /etc/resolv.conf

nameserver 192.168.0.1
nameserver 8.8.8.8
nameserver 8.8.4.4

You can try to restart your system networking to check whether the problem of being unable to ping domain names is resolved. See the section “Restart Networking” of this post.

Configuring Default Route Gateway

You need to check your route table and check if the destination host 0.0.0.0 is routed to the default gateway IP (e.g. 192.168.0.1). If not you need to update the gateway IP.

Get Default Gateway IP

$ ip r | grep default
default via 192.168.0.1 dev eth0 proto dhcp metric 100

Some computers might have multiple default gateways. The gateway with lowest Metric is the first to be searched and used as the default gateway.

My server’s default gateway IP is 192.168.0.1.

Check the Route Table

Print the route table:

$ sudo route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
...
  • Destination: The destination network or destination host.
  • Gateway: The gateway address or ’*’ if none set.
  • Genmask: The netmask for the destination net: 255.255.255.255 for a host destination and 0.0.0.0 for the default route.

What Is The Meaning of 0.0.0.0 In Routing Table?

Each network host has a default route for each network card. This will create a 0.0.0.0 route for such card. The address 0.0.0.0 generally means “any address”. If a packet destination doesn’t match an individual address in the table, it must match a 0.0.0.0 gateway address. In other words, default gateway is always pointed by 0.0.0.0

Update the 0.0.0.0 Route to the Default Gateway

Update the destination host 0.0.0.0 route the the default gateway IP e.g 192.168.0.1.

ip command

You can temporarily update the 0.0.0.0 route gateway by the ip command.

Add the default route:

ip route add default via 192.168.0.1

You can also delete the default route:

ip route delete default

route command

You can temporarily update the 0.0.0.0 route gateway by the route command.

Add the default route:

route add default gw 192.168.0.1

You can also delete the default route:

route del default gw 192.168.0.1

Update configuration file

You can permanently update the 0.0.0.0 route gateway by in system configuration file.

CentOS/RHEL

vim /etc/sysconfig/network

Add the following content to the file /etc/sysconfig/network

NETWORKING=yes
GATEWAY=192.168.0.1

Debian/Ubuntu

vim /etc/network/interfaces

Find network interface and add the following option

... 
gateway 192.168.0.1
...

Restart Networking

After update the gateway configuration file, you need restart the networking.

Restart the networking on CentOS/RHEL

sudo systemctl restart NetworkManager.service
# or
sudo systemctl stop NetworkManager.service
sudo systemctl start NetworkManager.service

Restart the networking on Debian/Ubuntu

sudo /etc/init.d/networking restart

Appendixes

Some public DNS servers

# OpenDNS
208.67.222.222
208.67.220.220

# Cloudflare
1.1.1.1
1.0.0.1

# Google
8.8.8.8
8.8.4.4

# Quad9
9.9.9.9

References

[1] Understanding Routing Table

[2] What Is The Meaning of 0.0.0.0 In Routing Table?

介绍麒麟操作系统

银河麒麟(NeoKylin)是由中国麒麟软件有限公司基于Linux开发的商业操作系统。其社区版为Ubuntu Kylin。中标麒麟(NeoKylin)与银河麒麟同为中国麒麟软件有限公司基于Linux开发的商业操作系统。

银河麒麟高级服务器操作系统V10(Kylin Linux Advanced Server V10 (Tercel))是针对企业级关键业务,适应虚拟化、云计算、大数据、工业互联网时代对主机系统可靠性、安全性、性能、扩展性和实时性等需求,依据CMMI5级标准研制的提供内生本质安全、云原生支持、自主平台深入优化、高性能、易管理的新一代自主服务器操作系统。银河麒麟系统采用同源构建支持六款自主CPU平台(飞腾、鲲鹏、龙芯、申威、海光、兆芯等国产CPU),所有组件基于同一套源代码构建。

查看操作系统信息

# 查看 Linux 系统发行版
$ cat /etc/os-release
NAME="Kylin Linux Advanced Server"
VERSION="V10 (Tercel)"
ID="kylin"
VERSION_ID="V10"
PRETTY_NAME="Kylin Linux Advanced Server V10 (Tercel)"
ANSI_COLOR="0;31"
# 查看 CPU 架构
$ lscpu
Architecture:                    aarch64
CPU op-mode(s): 64-bit
Model name: Kunpeng-920
...
Details
Architecture:                    aarch64
CPU op-mode(s): 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 1
Core(s) per socket: 4
Socket(s): 1
NUMA node(s): 1
Vendor ID: HiSilicon
Model: 0
Model name: Kunpeng-920
Stepping: 0x1
BogoMIPS: 200.00
NUMA node0 CPU(s): 0-3
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; __user pointer sanitization
Vulnerability Spectre v2: Not affected
Vulnerability Tsx async abort: Not affected
Flags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma dcpop asimddp asimdfhm ssbs

配置 yum 源仓库

使用中标软件的 yum 源仓库

# 备份系统原来的 yum 配置
mv /etc/yum.repos.d/kylin_aarch64.repo /etc/yum.repos.d/kylin_aarch64.repo.bak
# 创建新的 yum 源配置文件
vi /etc/yum.repos.d/kylin_aarch64.repo

将下面的内容添加到 /etc/yum.repos.d/kylin_aarch64.repo 文件中

[ks10-adv-os]
name=Kylin-Linux-Advanced-Server-os
baseurl=http://update.cs2c.com.cn:8080/NS/V10/V10SP1/os/adv/lic/base/aarch64/
gpgcheck=0
enable=1

baseurl格式为 http://update.cs2c.com.cn:8080/NS/V10/{版本}/os/adv/lic/base/{架构}/

这里的版本选择的是 V10SP1,架构选的是 aarch64(鲲鹏)。

# 清除原有 yum 缓存和生成新的缓存
$ sudo yum clean all && sudo yum makecache
# 测试
$ sudo yum update
$ sudo yum install java-1.8.0-openjdk
Is this ok [y/N]: N

介绍 CTyunOS

天翼云操作系统 CTyunOS 是基于欧拉开源操作系统(openEuler,简称“欧拉”)开发的,欧拉操作系统是华为基于 CentOS 开发的。2019年9月,华为宣布 EulerOS 开源,开源名称为 openEuler(开源欧拉)。EulerOS 支持 AArch64(鲲鹏)处理器、容器虚拟化技术,是一个面向企业级的通用服务器架构平台。华为的鸿蒙是手机手表的操作系统,面向C端。而欧拉是电脑服务器的操作系统,是面向B端。

CTyunOS 操作系统基于 openEuler 20.03 LTS 版本自主研发的。CTyunOS 3 是 CTyunOS 在2023年4月发布的最新版本,上游采用了openEuler社区发布的长期稳定版本 openEuler 22.03 LTS SP1作为基线,针对云计算、云原生场景进行了深度的开发,目前在天翼云上已经可以开通该操作系统的弹性云主机。

查看操作系统信息

# 查看 Linux 系统发行版
$ cat /etc/os-release
NAME="ctyunos"
VERSION="2.0.1"
ID="ctyunos"
VERSION_ID="2.0.1"
PRETTY_NAME="ctyunos 2.0.1"
ANSI_COLOR="0;31"
# 查看 CPU 架构
$ lscpu
Architecture:                    aarch64
CPU op-mode(s): 64-bit
Model name: Kunpeng-920
...
Details
Architecture:                    aarch64
CPU op-mode(s): 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 1
Core(s) per socket: 4
Socket(s): 1
NUMA node(s): 1
Vendor ID: HiSilicon
Model: 0
Model name: Kunpeng-920
Stepping: 0x1
BogoMIPS: 200.00
NUMA node0 CPU(s): 0-3
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; __user pointer sanitization
Vulnerability Spectre v2: Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Flags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma dcpop asimddp asimdfhm ssbs

配置 yum 源仓库

# 备份系统原来的 yum 配置
$ mv ctyunos.repo ctyunos.repo.bak
# 下载华为云的 openeuler yum 源配置文件
$ curl -O https://repo.huaweicloud.com/repository/conf/openeuler_aarch64.repo
# 移动到系统的 yum 源配置目录
$ mv openeuler_aarch64.repo /etc/yum.repos.d
# 清除原有 yum 缓存和生成新的缓存
$ sudo yum clean all && yum makecache
# 测试
$ sudo yum update
$ sudo yum install java-1.8.0-openjdk
Is this ok [y/N]: N

华为云 Linux 软件包仓库配置文件目录:https://repo.huaweicloud.com/repository/conf/

References

[1] Configuring Yum and Yum Repositories - RedHat

[2] 配置OpenEuler的网络yum源

[3] CentOS配置yum仓库的三种方法

0%