← All writing

Java

A Java learning reference spanning core language features, reflection, concurrency and I/O, then expanding into Maven, Spring Boot, caching, messaging, microservices and deployment tools.

Java

Basic

Input

java
import java.util.Scanner;

public class test 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        
    }
}

Array

java
//Array is created in heap by new.
//Initial value will be zero.
int[] a = new int[10];

int[] b = new int[]{1, 2, 3, 4}
int[] c = {1, 2, 3, 4} //short write thus it's in heap


//Copy is not complete.
int[] d = c;
d[0] = 100; //Then c[0] will be 100.

Method

java
public static int f(int a, int b)
{
    return a + b;
}

//Overload
public static int f(int a, int b, int c)
{
    return a + b + c;
}

Class

java
//One file can only have one public class with the same name of file itself.
public class saber 
{
    //static will let all instance share the same value.
   	//and will be placed special place in heap. 
    static String name;
    int age;
    public void fight()
    {
        System.out.println("fight!!!");
    }
}

In Java, there is a special class with the name Class. It describe the some comme property of class.

java
public final class Class<T> implements ... {
	...
}

How could we create a instance of Class

java
// 1. Use Class.forName Since Class.forName is static and it can be applied
// without a instance

//Note: Class.forName need fully qualified name
// (which includes the package name)
Class <?> clazz = Class.forName("exercise.reflection.reflectionClass")


// 2. The className.class syntax is a static way 
// to get the Class object of a class at compile time. 
// In Java, every class has a Class object associated with it. 
Class<?> clazz2 = reflectionClass.class;


// 3. Use the instance of specified class
reflectionClass r = new reflectionClass();
Class<?> class3 = r.getClass();

And it has many methods to get the information of our specified class

java
// Get the constructor of specified class
Constructor<?>[] cons = clazz1.getConstructors();

//Get the field of specified class
Field[] field = clazz1.getFields();

//Get the method of specified class
Method[] method = clazz1.getMethods();

Note: interface also has its own Class instance. So we can use this to handle annotation which is in fact a interface.

String Series

String

Immutable sequence of characters.

  • Once created, cannot be changed. Any modification creates a new object.

  • Stored in the String Pool (for literals) to save memory and improve performance.

  • Safe to use across threads (immutable).

java
//string is a reference

//This is a constant string placed in a special area of heap.
String s = "saber"; 
String ss = "saber"; 
String sss = new String("saber")

// == compare the reference i.e. address of string not the string.
ss == s //this result is true since ss will point the same constant string.

s == sss // this is false since the address of strings is different.
    
//s[0] is not defined.
s.charAt(0)

StringBuilder

Mutable sequence of characters, not thread-safe.

  • Can be modified without creating new objects.

  • Faster than StringBuffer because it doesn’t synchronize methods.

java
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World")
System.out.println(sb); // Hello World

String s = sb.toString();

StringBuffer

Mutable sequence of characters, thread-safe.

  • Similar to StringBuilder, but all methods are synchronized.

  • Older class (exists since Java 1.0).

  • Slower than StringBuilder because of synchronization overhead.

java
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Hello World

Concatenation

Using + to concatenate string.

java
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + s2; // HelloWorld

NOTE:

  • If both sides are string literals, the compiler optimizes it at compile time:
java
String s = "Hello" + "World"; // compiler turns into "HelloWorld"

  • If at least one part is not known at compile time, the compiler creates a StringBuilder behind the scenes:
java
String s = s1 + s2;
// Compiler turns into:
String s = new StringBuilder().append(s1).append(s2).toString();

Performance Considerations

  • + is fine for small concatenations.
  • In loops, always use StringBuilder (or StringBuffer if multithreaded).

Enum

An enum (short for enumeration) is a special Java type used to define a collection of constants.

java
// define
public enum OperationType {

    /**
     * 更新操作
     */
    UPDATE,

    /**
     * 插入操作
     */
    INSERT
}

// use
public void doSomething(OperationType type) {
    if (type == OperationType.INSERT) {
        // insert logic
    } else if (type == OperationType.UPDATE) {
        // update logic
    }
}

Extend

java

Collection

Code
              Collection (interface)
               /     |       \
         List     Set     Queue  <- interfaces
          |        |        |
  ArrayList  HashSet  LinkedList <- classes

Use map or stream operation on List:

java
list.stream().map(()-> ...).toList();

Serializable

Serializable is a marker interface in Java (java.io.Serializable) that tells the Java Virtual Machine (JVM) a class can be converted into a byte stream, which can then be:

Saved to a file

Sent over a network

Stored in memory (e.g., in Redis)

Reconstructed (deserialized) later

Interface

In Java, an interface is a contract that specifies what a class should do, but not how it should do it.

Think of it like:

A checklist of methods your class must implement.

FeatureDetails
Access ModifierAll interface methods are implicitly public and abstract (unless default, static, or private).
FieldsAll fields are public static final (constants).
Multiple ImplementationA class can implement multiple interfaces.
No ConstructorsInterfaces can’t be instantiated or have constructors.
No StateInterfaces can’t store instance variables.

Note:

A method marked abstract:

  • Has no body.

  • Can only appear inside abstract classes or interfaces.

  • Must be overridden by the first concrete subclass.

Default methods (Java 8+)

Provide a default implementation of methods.

java
interface Animal {
    default void sleep() {
        System.out.println("Sleeping...");
    }
}

Generics

Create a generic class

Generic Class

java
// use T as the type
public class genericsClass<T> {
    
    private T value;

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

// Multiple type Parameters
class Test<T, U>
{
    T obj1;  // An object of type T
    U obj2;  // An object of type U

    // constructor
    Test(T obj1, U obj2)
    {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    // To print objects of T and U
    public void print()
    {
        System.out.println(obj1);
        System.out.println(obj2);
    }
}

Use it

java
public class generics {
    public static void main(String[] args) {
        // Note: type must be a reference type
        genericsClass<Integer> g = new genericsClass<>();
        
        g.setValue(100);

        System.out.println(g.getValue());
    }
}

Unbounded wildcard ? is used when specifying a concrete type, so it can receive any type

java
public class generics {
    public static void main(String[] args) {

        // Note: type must be a reference type
        genericsClass<Integer> g1 = new genericsClass<>();
        genericsClass<String> g2 = new genericsClass<>();
        
        //Thus we use <?> to receive <Integer> and <String>
        show(g1);
        show(g2);
    }

    // Here we must specify concrete type like Integer or String
    private static void show(genericsClass<?> x){
        System.out.println(x.getValue());
    }
}

Generic Method

If we want to use Generic Method in a non-generic class, we need to specify type parameters before function by <>.

java
class Geeks {
    
    // A Generic method example
    // Use <T> to tell compiler to use Generic Method.
    static <T> void genericDisplay(T element)
    {
        System.out.println(element.getClass().getName()
                           + " = " + element);
    }

    // Driver method
    public static void main(String[] args)
    {
        // Calling generic method with Integer argument
        genericDisplay(11);

        // Calling generic method with String argument
        genericDisplay("GeeksForGeeks");

        // Calling generic method with double argument
        genericDisplay(1.0);
    }
}

Reflection

java
public class reflection {

    public static void main(String[] args) throws ClassNotFoundException {
        
        //Note: Class.forName need fully qualified name 
        // (which includes the package name)
        // Class.forName is static
        Class<?> clazz1 = Class.forName("exercise.reflection.reflectionClass");
        
        // The className.class syntax is a static way 
        // to get the Class object of a class at compile time. 
        // In Java, every class has a Class object associated with it. 
        Class<?> clazz2 = reflectionClass.class;
        
        // Use the instance of specified class
        reflectionClass r = new reflectionClass();
        Class<?> class3 = r.getClass();
        
        // Get the constructor of specified class
        Constructor<?>[] cons = clazz1.getConstructors();
        for (Constructor<?> x : cons) {
            System.out.println(x);
        }
        
        //Get the field of specified class
        Field[] field = clazz1.getFields();
        
        for (Field x : field) {
            System.out.println(x);
        }

        //Get the method of specified class
        Method[] method = clazz1.getMethods();
        
    }
}

Multiple Thread

extend Thread class

Extend Thread class and override run method.

java
package exercise.thread;

public class MultiThreadClass extends Thread {
    @Override
    public void run() {
        for(int i = 0; i<= 100; i++)
            System.out.println(getName() + "hello world!");   
    }
}

Then use start() method to run.

java
package exercise.thread;

public class MultiThread {
    public static void main(String[] args) {
        MultiThreadClass multiThreadClass1 = new MultiThreadClass();
        MultiThreadClass multiThreadClass2 = new MultiThreadClass();
        
        multiThreadClass1.setName("1: ");
        multiThreadClass2.setName("2: ");

        multiThreadClass1.start();
        multiThreadClass2.start();
    }
}

Implement Runable interface

Same as before, we need to override run method.

java
package exercise.thread;

public class RunnableClass implements Runnable{
    
    @Override
    public void run() {
        for(int i = 0; i<= 100; i++)
            System.out.println(Thread.currentThread().getName() + "hello world!");   
    }
}

Then we need use this to construct a Thread object.

java
package exercise.thread;

public class MultiThread {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        RunnableClass r1 = new RunnableClass();

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);
        t1.setName("1: ");
        t2.setName("2: ");
        
        t1.start();
        t2.start();
    }
}

Implement Callable<>

This is used when we need a return value. And the generic parameter is used to specify the type of return value.

java
package exercise.thread;

import java.util.concurrent.Callable;

public class CallableClass implements Callable<Integer>{
    
    @Override
    public Integer call() throws Exception {
        Integer res = 0;
        for(int i =1; i<=100; i++)
            res += i;
        return res;
    }
}

Then we need Feature and Thread to run it.

java
package exercise.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class MultiThread {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        RunnableClass r1 = new RunnableClass();

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);
        t1.setName("1: ");
        t2.setName("2: ");
        
        t1.start();
        t2.start();

        CallableClass c = new CallableClass();

        FutureTask<Integer> ft = new FutureTask<>(c);
        Thread t = new Thread(ft);
        t.start();
        System.out.println(ft.get());
    }
}

synchronized

java
// synchronized code block.
// Only get the lock, code can be executed.
synchronized(lock object) {
    // ...
}

It can be used in method and class.

java
private synchronized void method() {
	// ...
}

// Then the lock object is this
// if the method is static then lock object is method.class

Lock

Lock is a interface and we can use it to control lock manually.

java
Lock lock = new ReentrantLock();

lock.lock();
// ...
lock.unlock();

thread pool

java
public class MultiThread {
    public static void main(String[] args) {

        // Create thread pool
        ExecutorService pool = Executors.newFixedThreadPool(3);

        // Create 3 thread
        pool.submit(new RunnableClass());
        pool.submit(new RunnableClass());
        pool.submit(new RunnableClass());

    }
}

Use ThreadPoolExecutor.

java
    /**
     * 用给定的初始参数创建一个新的ThreadPoolExecutor。
     */
    public ThreadPoolExecutor(int corePoolSize,//线程池的核心线程数量
                              int maximumPoolSize,//线程池的最大线程数
                              long keepAliveTime,//当线程数大于核心线程数时,多余的空闲线程存活的最长时间
                              TimeUnit unit,//时间单位
                              BlockingQueue<Runnable> workQueue,//任务队列,用来储存等待执行任务的队列
                              ThreadFactory threadFactory,//线程工厂,用来创建线程,一般默认即可
                              RejectedExecutionHandler handler//拒绝策略,当提交的任务过多而不能及时处理时,我们可以定制策略来处理任务
                               ) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

I/O

Byte stream (formally, say binary file)

There is no practical difference between a byte file and a binary file — they both refer to files that store raw binary data (not text). However, "binary file" is the standard and widely accepted term.

Character stream

It need to encode and decode (like UTF-8).

Custom Annotations

java
@Retention(RetentionPolicy.RUNTIME) // Available at runtime
@Target(ElementType.METHOD)         // Can be used on methods
public @interface AutoFill {
    
    // Note: the field is represented as method.
    OperationType value();
    
    // use default to set default value
    
    String hello() default "saber";
}

Use reflection to test whether there is such annotation and execute corresponding annotation behavors.

Then we can add this annotation to any method.

Proxy

A proxy is an object that stands in for another object. It has the same interface as the “real” object, but it can:

  • Add extra behavior (logging, caching, security checks, etc.)
  • Control access to the real object
  • Delay creating the real object until it’s needed

Think of it like a personal assistant:

Instead of you talking to the CEO directly, you talk to their assistant, who can filter, log, or change the request before passing it on.

Static Proxy

  • You write a separate class that implements the same interface as the target.

  • You manually forward calls to the real object.

java
interface Service {
    void doWork();
}

// This is real class, and we want to do proxy on it
class RealService implements Service {
    public void doWork() {
        System.out.println("Doing work...");
    }
}

// This is our proxy, it contain our real object and do something
// before and after call real object service.
class ServiceProxy implements Service {
    private RealService realService;

    public ServiceProxy(RealService realService) {
        this.realService = realService;
    }

    public void doWork() {
        System.out.println("Logging before work");
        realService.doWork();
        System.out.println("Logging after work");
    }
}

public class Main {
    public static void main(String[] args) {
        Service service = new ServiceProxy(new RealService());
        service.doWork();
    }
}

Dynamic Proxy (Java Reflection API)

  • Added in Java 1.3.

  • You don’t manually write the proxy class — the JVM generates it at runtime.

  • Works only with interfaces (for classes, you’d use something like library CGLIB).

We use a static method newProxyInstance() in class Proxy to create proxy object.

java
import java.lang.reflect.*;

interface Service {
    void doWork();
}

class RealService implements Service {
    public void doWork() {
        System.out.println("Doing work...");
    }
}

// Define how to handle proxy behavior.
class LoggingHandler implements InvocationHandler {
    private Object target;
    public LoggingHandler(Object target) {
        this.target = target;
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before: " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("After: " + method.getName());
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        Service realService = new RealService();
        Service proxy = (Service) Proxy.newProxyInstance(
            Service.class.getClassLoader(),
            new Class<?>[]{Service.class},
            new LoggingHandler(realService)
        );

        proxy.doWork();
    }
}

Object class

In Java, Object is the ultimate superclass — the root of the entire class hierarchy.

Every single class in Java directly or indirectly inherits from java.lang.Object. If you don’t explicitly extend another class, your class automatically extends Object.

Commonly Used Methods in Object

MethodPurpose
toString()Returns a string representation of the object. Default: class name + hash code. Usually overridden.
equals(Object obj)Compares two objects for equality. Default: compares memory addresses (same reference). Usually overridden.
hashCode()Returns an integer hash code. Used in hash-based collections (HashMap, HashSet).
getClass()Returns the runtime class of the object.
clone()Creates and returns a copy of the object (requires Cloneable)

yml

yml
# define object/map set
user:
    name: Tom
    age: 18
    gender: male


# define array/List
hobby:
    - Java
    - game
    - sport

Maven

Create Projcet

Create a project with a archetype.

sh
mvn archetype:generate \
  -DarchetypeGroupId=io.github.fuzhengwei \
  -DarchetypeArtifactId=ddd-scaffold-lite-v2 \
  -DarchetypeVersion=2.4 \

Basic

We can use <groupId>, <artifactId> and <version> to uniquely identify one maven module or project.

Parent POM:

xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

    <!-- parent project -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.4.4</version>
	</parent>
	
    <!-- self unique identification -->
    <groupId>com.altria</groupId>
	<artifactId>sky</artifactId>
	<version>0.0.1-SNAPSHOT</version>

    <!-- *NOTE*: the packaging type for a parent POM should be set to pom -->
    <packaging>pom</packaging>

    <!-- sub-module -->
    <modules>
        <module>sky-common</module>
        <module>sky-pojo</module>
        <module>sky-server</module>
    </modules>

    <!-- This is used to define custom variables (properties) -->
    <!-- Thus we can use it to specify version -->
	<properties>
		<java.version>21</java.version>
        <mybatis.spring>3.0.4</mybatis.spring>
        <pagehelper>1.4.6</pagehelper>
        <aliyun.sdk.oss>3.17.4</aliyun.sdk.oss>
        <jjwt>0.11.5</jjwt>
        <jaxb-api>2.3.1</jaxb-api>
	</properties>

    <!-- is used to centralize and control the versions of dependencies -->
    <!-- used throughout a multi-module project -->
    <!-- Then sub-module need not to declare the version -->
  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring}</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>

            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>${pagehelper}</version>
            </dependency>

            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt</artifactId>
                <version>${jjwt}</version>
            </dependency>

            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>${aliyun.sdk.oss}</version>
            </dependency>

            <dependency>
                <groupId>javax.xml.bind</groupId>
                <artifactId>jaxb-api</artifactId>
                <version>${jaxb-api}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>
</project>

exclusion

We use <exclusion> to exclued some transitive dependency

xml
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <exclusions>
        <exclusion>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Command

check version

powershell
mvn -v

Annotaction

Lombok

java
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class User {
    private Long id;
    private String username;
    private String email;
}

@Data will add all coresponding getter and setter for all fields or attributes.

@Builder can simply constructor. For example:

java
User user = User.builder()
                .id(1L)
                .username("Saber")
                .email("Saber@example.com")
                .build();

Spring doc OpenAPI

AnnotationDescription
@OpenAPIDefinitionDefine global OpenAPI configuration (e.g., title, version).
@OperationDescribes a single API operation (summary, description, tags).
@ApiResponseDescribes responses for an operation.
@ParameterAdd detailed parameter info (name, description, required, etc).
@RequestBodyDescribe the request body content.
@SchemaDescribes a model class or field in more detail (e.g., type, format).
@TagGroups endpoints under specific tags in Swagger UI.
@HiddenExclude a method, class, or parameter from Swagger documentation.

It’s used to generate API documentation for your Spring Boot project.

Spring boot

Global exception handler

java
@RestControllerAdvice // This.
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler // And this.
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
}

@Bean

This is used at method.(However @component is used at class)

It let the returned class of method be managed by IOC container.

The @Bean annotation is used on a method to indicate that the return value of the method should be registered as a bean in the Spring context.

A bean is simply an object that is managed by the Spring IoC container (Inversion of Control). Spring handles its creation, lifecycle, and dependencies for you.

It’s usually used inside a class annotated with @Configuration.

java
@Slf4j
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Bean
    public Docket docket() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
}

OpenAPI and Knife4j

Dependencies

pom
<!-- OpenAPI and knife4j -->
<springdoc>2.8.6</springdoc>
<knife4j>4.4.0</knife4j>

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>${springdoc}</version>
</dependency>

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
    <version>${knife4j}</version>
</dependency>

Configuration

java
@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Blog Platform API")
                        .description("API documentation for the Blog Platform backend.")
                        .version("1.0.0"));
    }

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("blog-user")
                .packagesToScan("altria.blog_server.controller.user")
                .pathsToMatch("/**")
                .build();
    }

    @Bean
    public GroupedOpenApi adminApi() {
        return GroupedOpenApi.builder()
                .group("blog-admin")
                .packagesToScan("altria.blog_server.controller.admin")
                .pathsToMatch("/**")
                .build();
    }
}

How to use

  • Swagger UI: Visit /swagger-ui.html after starting the server for the standard OpenAPI UI.
  • Knife4j UI (Recommendation): Visit /doc.html for the enhanced Knife4j documentation interface.
  • API groups are separated for user and admin endpoints for easier navigation.

JWT

Docker

Basics

core terms

Image: A snapshot of a file system (like a recipe).

Container: A running instance of an image (like a dish made from the recipe).

Dockerfile: A script to build a Docker image.

--help (Useful!!)

Run 'docker COMMAND --help' for more information on a command.

e.g.

Code
docker network --help

Usage:  docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

docker ps

It lists all running containers on your system. When adding -a, it will include stopped containers.

Code
docker ps         # Running containers
docker ps -a      # All containers (running + stopped)

docker inspect

docker inspect <container> to check all information about a container.

docker images

List all images which have been downloaded.

Code
PS > docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    74cc54e27dc4   6 months ago   10.1kB
redis         7.4       65750d044ac8   7 months ago   117MB

docker run

Create and start a new container from an image.

If such image doesn’t already exist locally it will pull the image from Docker Hub (i.e. remote repository).

sh
docker run -d --name my-container -p 80:80 nginx

run: Create anb starts a container from an image

-d: Detached (runs in background)

--name: Name your container

-p: Maps local port to container port

nginx: an specific image.

docker pull

Download images from Docker Hub.

Code
docker pull nginx

docker rmi

Delete an image wich is already downloaded.

shell
docker rmi nginx

docker start

Start an existing container.

Code
PS > docker start redis
redis

docker stop

Stop a running container.

docker exec

Code
docker exec [OPTIONS] <container> <command>

This command lets you run a command inside a running container.

It does not start a new container — it just interacts with an existing one.

e.g.

Code
docker exec -it my-container bash

-i: interactive mode (keeps STDIN open)

-t: pseudo-TTY (makes it act like a terminal)

bash: the command to run — opens a bash shell

e.g.

Run redis command line interface in a container wich contains redis.

sh
docker exec -it redis redis-cli

docker network

Create a network

sh
docker network create <myNetwork>

Use --network <myNetwork> to connect network when creating a container.

Code
docker run -d \
  --name mysql \
  -p 3306:3306 \
  -e TZ=Asia/Shanghai \
  -e MYSQL_ROOT_PASSWORD=123 \
  -v ./mysql/data:/var/lib/mysql \
  -v ./mysql/conf:/etc/mysql/conf.d \
  -v ./mysql/init:/docker-entrypoint-initdb.d \
  --network hm-net\
  mysql

docker volume

Create a share directory between host and container (bijective map).

Code
docker run -d \
  --name mysql \
  -p 3306:3306 \
  -e TZ=Asia/Shanghai \
  -e MYSQL_ROOT_PASSWORD=123 \
  -v ./mysql/data:/var/lib/mysql \
  -v ./mysql/conf:/etc/mysql/conf.d \
  -v ./mysql/init:/docker-entrypoint-initdb.d \
  --network hm-net\
  mysql

-v ./mysql/data:/var/lib/mysql: set a bijective map between ./mysql/data in host and /var/lib/mysql in container

-v ./mysql/conf:/etc/mysql/conf.d is simiar.

Run redis

Create a container with redis in it.

shell
docker run -d --name redis -p 6379:6379 redis:<version>

Run redis

shell
docker exec -it redis redis-cli

docker compose

Instead of starting each container manually with long docker run commands, Docker Compose lets you describe your entire application — including all its services, networks, and volumes — in a single YAML file, usually named docker-compose.yml.

yml
# 命令执行 docker-compose -f docker-compose-environment.yml up -d
version: '3.9'
services:
  # 注册中心 https://github.com/nacos-group/nacos-docker - 其他配置可参考(集群)
  # http://127.0.0.1:8848/nacos 【账号:nacos 密码:nacos】
  nacos:
    image: nacos/nacos-server:v2.2.3-slim
    container_name: nacos
    restart: always
    ports:
      - "8848:8848"
      - "9848:9848"
    environment:
      - PREFER_HOST_MODE=hostname
      - MODE=standalone
      - SPRING_DATASOURCE_PLATFORM=mysql
      - MYSQL_SERVICE_HOST=mysql
      - MYSQL_SERVICE_DB_NAME=nacos_config
      - MYSQL_SERVICE_PORT=3306
      - MYSQL_SERVICE_USER=root
      - MYSQL_SERVICE_PASSWORD=123456
      - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
      - NACOS_AUTH_IDENTITY_KEY=2222
      - NACOS_AUTH_IDENTITY_VALUE=2xxx
      - NACOS_AUTH_TOKEN=SecretKey012345678901234567890123456789012345678901234567890123456789
    networks:
      - my-network
    depends_on:
      mysql:
        condition: service_healthy

  mysql:
    image: mysql:8.0.32
    container_name: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      TZ: Asia/Shanghai
      MYSQL_ROOT_PASSWORD: 123456
    ports:
      - "13306:3306"
    volumes:
      - ./mysql/sql:/docker-entrypoint-initdb.d
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
      interval: 5s
      timeout: 10s
      retries: 10
      start_period: 15s
    networks:
      - my-network

  # phpmyadmin https://hub.docker.com/_/phpmyadmin
  phpmyadmin:
    image: phpmyadmin:5.2.1
    container_name: phpmyadmin
    hostname: phpmyadmin
    ports:
      - 8899:80
    environment:
      - PMA_HOST=mysql
      - PMA_PORT=3306
      - MYSQL_ROOT_PASSWORD=123456
    depends_on:
      mysql:
        condition: service_healthy
    networks:
      - my-network

  # Redis
  redis:
    image: redis:6.2
    container_name: redis
    restart: always
    hostname: redis
    privileged: true
    ports:
      - 16379:6379
    volumes:
      - ./redis/redis.conf:/usr/local/etc/redis/redis.conf
    command: redis-server /usr/local/etc/redis/redis.conf
    networks:
      - my-network
    healthcheck:
      test: [ "CMD", "redis-cli", "ping" ]
      interval: 10s
      timeout: 5s
      retries: 3

  # RedisAdmin https://github.com/joeferner/redis-commander
  # 账密 admin/admin
  redis-admin:
    image: spryker/redis-commander:0.8.0
    container_name: redis-admin
    hostname: redis-commander
    restart: always
    ports:
      - 8081:8081
    environment:
      - REDIS_HOSTS=local:redis:6379
      - HTTP_USER=admin
      - HTTP_PASSWORD=admin
      - LANG=C.UTF-8
      - LANGUAGE=C.UTF-8
      - LC_ALL=C.UTF-8
    networks:
      - my-network
    depends_on:
      redis:
        condition: service_healthy

  # rabbitmq
  # 账密 admin/admin
  # rabbitmq-plugins enable rabbitmq_management
  rabbitmq:
    image: rabbitmq:3.12.9
    container_name: rabbitmq
    restart: always
    ports:
      - "5672:5672"
      - "15672:15672"
    environment:
      RABBITMQ_DEFAULT_USER: admin
      RABBITMQ_DEFAULT_PASS: admin
    command: rabbitmq-server
    volumes:
      - ./rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins

networks:
  my-network:
    driver: bridge

Use

Code
docker compose -f docker-compose-environment.yml up -d

-d

  • Stands for detached.
  • Runs the containers in the background (so your terminal is free).
  • Without -d, logs will be shown in your terminal and you have to keep it open.

-f

  • Stands for file.
  • Specifies which Compose YAML file to use.
  • Default is docker-compose.yml.

up: Create and start containers

Redis

Use in java

1. Add Redis dependency

If you use Maven, include this in your pom.xml:

Code
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Configure Redis connection

In application.yml or application.properties, configure Redis:

application.yml

yml
spring:
  redis:
    host: localhost
    port: 6379
    password:               # optional
    database: 0

Make sure Redis is running locally (redis-server).


3. Use StringRedisTemplate or RedisTemplate

Spring Boot automatically provides two templates:

  • StringRedisTemplate → for String keys and values
  • RedisTemplate<Object, Object> → for more complex objects

Example using StringRedisTemplate:

java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisTestController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/test")
    public String testRedis() {
        // Set a value
        redisTemplate.opsForValue().set("myKey", "Hello Redis!");
        
        // Get the value
        String value = redisTemplate.opsForValue().get("myKey");
        return "Value from Redis: " + value;
    }
}


4. Store Java objects

If you want to store POJOs, use a RedisTemplate with a serializer.

Example configuration:

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        template.afterPropertiesSet();
        return template;
    }
}

Then you can use it like:

java
@Autowired
private RedisTemplate<String, Object> redisTemplate;

public void saveUser(User user) {
    redisTemplate.opsForValue().set("user:1", user);
}

public User getUser() {
    return (User) redisTemplate.opsForValue().get("user:1");
}

Use redisson

1.Add dependency

Code
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.37.0</version>  <!-- use latest -->
</dependency>

2. Configure Redis connection

yml
spring:
  redis:
    host: localhost
    port: 6379

# OR using Redisson's native config:
redisson:
  singleServerConfig:
    address: "redis://127.0.0.1:6379"
    password: null
    database: 0

3.Inject and use RedissonClient

java
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class RedissonDemoController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/redisson")
    public String test() {
        // Get a Redis object bucket (like key-value)
        RBucket<String> bucket = redissonClient.getBucket("hello");
        bucket.set("Hello Redisson!");
        return bucket.get();
    }
}

NOTE: Redisson’s key–value API (getBucket) doesn’t give you the raw Redis value directly, but instead gives you an RBucket object.

Help

help command is truely useful!!

Code
help @set

help @hash

Spring Cache

@CachePut

java
// Then the key is prfix::suffix
// and value is the return value of method.
// Put this key value into cache after method is executed.
@CachePut(cacheName = "prfix",  key = "suffix")

// Use #parameter to let the suffix be the parameter.
@CachePut(cacheName = "prfix",  key = "#parameter")

@Cacheable

First check if there is in cache. If yes then return.

Otherwise execute the method and put return value into cache.

key name is the rule as @CachePut

java
@CachePut(cacheName = "prfix",  key = "suffix")

@CacheEvict

Delete cache.

java
@CacheEvict(cacheNames = "setmealCache", allEntries = true)

Command

Show all keys

sh
keys *

Delete

This can delete all kinds of types.

sh
DEL key1 key2 key3 ... keyN

# Delete all the keys of all the existing databases
flushall

hash

Code
help @hash

    HKEYS key
    summary: Returns all fields in a hash.
    since: 2.0.0

    HDEL key field [field ...]
    summary: Deletes one or more fields and their values from a hash. Deletes the hash if no fields remain.
    since: 2.0.0

    HEXPIRE key seconds [NX|XX|GT|LT] FIELDS numfields field [field ...]
    summary: Set expiry for hash field using relative time to expire (seconds)
    since: 7.4.0
    
    HMGET key field [field ...]
    summary: Returns the values of all fields in a hash.
    since: 2.0.0

set

Redis CLI command

sh
help @set

	SADD key member [member ...]
  	summary: Adds one or more members to a set. Creates the key if it doesn't exist.
  	since: 1.0.0
  
  	SMEMBERS key
  	summary: Returns all members of a set.
 	since: 1.0.0
 	
	SCARD key
	summary: Returns the number of members in a set.
  	since: 1.0.0
  	
  	SINTER key [key ...]
    summary: Returns the intersect of multiple sets.
    since: 1.0.0
    
    SISMEMBER key member
  	summary: Determines whether a member belongs to a set.
  	since: 1.0.0
  	
  	SREM key member [member ...]
  	summary: Removes one or more members from a set. Deletes the set if the last member was removed.
  	since: 1.0.0
  	
  	....

Add a member into a set.

java
stringRedisTemplate.opsForSet().add(key, userId.toString());

Remove a member from a set.

java
stringRedisTemplate.opsForSet().remove(key, userId.toString());

Find if it is in a set.

java
String key = "blog:like:"+ blogId;
Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());

sorted-set

Every member has to be specified one score for sorting.

  1. Sorted by score (from lowest to highest) by default.
  2. If multiple elements have the same score, they're ordered lexicographically by value (i.e., string order).
Code
help @sorted-set

    ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...]
    summary: Adds one or more members to a sorted set, or updates their scores. Creates the key if it doesn't exist.
    since: 1.2.0
    
    ZCOUNT key min max
  	summary: Returns the count of members in a sorted set that have scores within a range.
  	since: 2.0.0
  	
  	ZRANGE key start stop [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES]
  	summary: Returns members in a sorted set within a range of indexes.
  	since: 1.2.0
  	
  	ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
  	summary: Returns members in a sorted set within a range of scores.
  	since: 1.0.5
  	
  	ZREM key member [member ...]
  	summary: Removes one or more members from a sorted set. Deletes the sorted set if all members were removed.
  	since: 1.2.0

Add one member

Code
stringRedisTemplate.opsForZSet().add(key, userId.toString(), score);

Find the score of one member

Code
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

Remove

Code
stringRedisTemplate.opsForZSet().remove(key, userId.toString());

Deployment

sh
maven clean package

and run .jar file background on server.

Code
nohup java -jar myapp-1.0.jar > app.log 2>&1 &

Environment-specific configuration

Use several application file.

You can create files like:

  • application-dev.yml
  • application-prod.yml
  • application-test.yml

and when run .jar use argument like

Code
# For development
java -jar your-app.jar --spring.profiles.active=dev

# For production
java -jar your-app.jar --spring.profiles.active=prod

Externalized Configuration

ou can place your configuration file outside the packaged JAR and point to it at runtime:

Code
java -jar your-app.jar --spring.config.location=/path/to/application-prod.yml

Microservice

Nacos

Service register

1.Add dependency.

xml
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

It's used for both registration and discovery.

2.Add configuration to application.yaml to specify the address of nacos server.

yaml
spring:
  cloud:
    nacos:
      server-addr: localhost:8848

Service discovery

1.Add same dependency

xml
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2.Add configuration to application.yaml to specify the address of nacos server.

yaml
spring:
  cloud:
    nacos:
      server-addr: localhost:8848

3.Construct service API using OpenFeign.

java
@FeignClient(name = "item-service")
public interface ItemClient {

    @GetMapping("/items")
    List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
}

4.Enable OpenFeign clients and call API

Add EnableFeignClients on spring boot class.

java
EnableFeignClients(basePackages = "com.hmall.api.client",
                defaultConfiguration = DefaultFeignConfig.class)
@MapperScan("com.hmall.cart.mapper")
@SpringBootApplication
public class CartApplication {
    public static void main(String[] args) {
        SpringApplication.run(CartApplication.class, args);
    }
}

Gateway

1.Add dependency

2.Add configuration to application.yaml.

yaml
spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: localhost:8848
    gateway:
      routes:
        - id: item-service
          uri: lb://item-service
          predicates:
            - Path=/items/**, /search/**

        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/users/**

        - id: cart-service
          uri: lb://cart-service
          predicates:
            - Path=/carts/**

        - id: trade-service
          uri: lb://trade-service
          predicates:
            - Path=/orders/**

        - id: pay-service
          uri: lb://pay-service
          predicates:
            - Path=/pay-orders/**

RabbitMQ

see 05-RabbitMQ快速入门--介绍和安装_哔哩哔哩_bilibili

When we don't specify the exchange, rabbitMQ will use the default exchange whoes name is "" (empty string).

Without a custom exchange, the routing key must be exactly the queue name.

Nacos

Dubbo

1.Add dependency to pom.

2.Add configuration.

yml
dubbo:
  application:
    name: big-market
    version: 1.0
  registry: 
    id: nacos-registry
    address: nacos://192.168.1.108:8848
  protocol:
    name: dubbo
    port: -1
  scan:
    base-packages: cn.bugstack.trigger.api

3.Add @EnableDubbo to Application class.

Zookeeper

1.Add dependency to pom

2.Create a client and make spring manage it.

java
@Configuration
@EnableConfigurationProperties(ZookeeperClientConfigProperties.class)
public class ZooKeeperClientConfig {

    /**
     * 多参数构建ZooKeeper客户端连接
     *
     * @return client
     */
    @Bean(name = "zookeeperClient")
    public CuratorFramework createWithOptions(ZookeeperClientConfigProperties properties) {
        ExponentialBackoffRetry backoffRetry = new ExponentialBackoffRetry(properties.getBaseSleepTimeMs(), properties.getMaxRetries());
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(properties.getConnectString())
                .retryPolicy(backoffRetry)
                .sessionTimeoutMs(properties.getSessionTimeoutMs())
                .connectionTimeoutMs(properties.getConnectionTimeoutMs())
                .build();
        client.start();
        return client;
    }
}

3.Usage

java
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class ZookeeperTest {
    
    @Resource
    private CuratorFramework curatorFramework;

        @Test
    public void test_all() throws Exception {
        String path = "/big-market-dcc/config/downgradeSwitch";
        String data = "0";
        curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(path, data.getBytes(StandardCharsets.UTF_8));

        for (int i = 0; i < 2; i++) {
            curatorFramework.setData().forPath(path, String.valueOf(i).getBytes(StandardCharsets.UTF_8));
        }
    }

    /**
     * 创建永久节点
     */
    @Test
    public void createNode() throws Exception {
        // create a persistent node on path with given data
        String path = "/big-market-dcc/config/downgradeSwitch/test/a";
        String data = "Saber";
        if (null == curatorFramework.checkExists().forPath(path)) {
            curatorFramework.create().creatingParentsIfNeeded()
                .forPath(path, data.getBytes(StandardCharsets.UTF_8));
        }
    }

    /**
     * 创建临时节点
     */
    @Test
    public void createEphemeralNode() throws Exception {
        String path = "/big-market-dcc/config/epnode";
        String data = "0";
        curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(path, data.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 创建临时有序节点
     */
    @Test
    public void crateEphemeralSequentialNode() throws Exception {
        String path = "/big-market-dcc/config/epsnode";
        String data = "0";
        curatorFramework.create()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(path, data.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 往节点种设置数据
     */
    @Test
    public void setData() throws Exception {
        curatorFramework.setData().forPath("/big-market-dcc/config/downgradeSwitch", "111".getBytes(StandardCharsets.UTF_8));
        curatorFramework.setData().forPath("/big-market-dcc/config/userWhiteList", "222".getBytes(StandardCharsets.UTF_8));
    }

    @Test
    public void getData() throws Exception {
        String downgradeSwitch = new String(curatorFramework.getData().forPath("/big-market-dcc/config/downgradeSwitch"), StandardCharsets.UTF_8);
        log.info("测试结果: {}", downgradeSwitch);
        String userWhiteList = new String(curatorFramework.getData().forPath("/big-market-dcc/config/userWhiteList"), StandardCharsets.UTF_8);
        log.info("测试结果: {}", userWhiteList);
    }

    /**
     * 异步修改数据
     */
    @Test
    public void setDataAsync() throws Exception {
        String path = "/big-market-dcc/config/downgradeSwitch";
        String data = "0";
        CuratorListener listener = (client, event) -> {
            Stat stat = event.getStat();
            log.info("stat=" + JSON.toJSONString(stat));
            CuratorEventType eventType = event.getType();
            log.info("eventType=" + eventType.name());
        };
        curatorFramework.getCuratorListenable().addListener(listener);
        curatorFramework.setData().inBackground().forPath(path, data.getBytes(StandardCharsets.UTF_8));
    }


    /**
     * 删除节点
     */
    @Test
    public void deleteData() throws Exception {
        String path = "/big-market-dcc/config/downgradeSwitch";
        curatorFramework.delete().deletingChildrenIfNeeded().forPath(path);
    }

    /**
     * 安全删除节点
     */
    @Test
    public void guaranteedDeleteData() throws Exception {
        String path = "/big-market-dcc/config/downgradeSwitch";
        curatorFramework.delete().guaranteed().forPath(path);
    }

    /**
     * 获取子节点下的全部子节点路径集合
     */
    @Test
    public void watchedGetChildren() throws Exception {
        String path = "/big-market-dcc";
        List<String> children = curatorFramework.getChildren().watched().forPath(path);
        log.info("测试结果:{}", JSON.toJSONString(children));
    }


    /**
     * 获取节点数据
     */
    @Test
    public void getDataByPath() throws Exception {
        String path = "/big-market-dcc/config/downgradeSwitch";
        String fullClassName = "";
        String jsonStr = new String(curatorFramework.getData().forPath(path), StandardCharsets.UTF_8);
        Class clazz = Class.forName(fullClassName);
        log.info("测试结果:{}", JSON.parseObject(jsonStr, clazz));
    }
}

AOP

See 134. SpringAOP-基础-核心概念_哔哩哔哩_bilibili

TermMeaning
AspectA class that contains the cross-cutting logic
PointcutWhich methods should be intercepted
AdviceWhat to do before/after/around the method
JoinPointThe actual method being intercepted
WeavingInjecting the extra logic into the method call

ElasticSearch

See Elasticsearch01-05.初识ES-基本概念_哔哩哔哩_bilibili

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.