[SpringCloud] - preliminary knowledge

Posted by mudasir on Thu, 10 Mar 2022 11:26:51 +0100

Microservice architecture is an architecture mode. It advocates dividing a single application into a group of small services. Services coordinate and cooperate with each other to provide final value for users. Each service runs in its own process, and services cooperate with each other through lightweight communication mechanism (usually RESTFUL API based on HTTP protocol). Each service is built around specific business and can be independently deployed to production environment and similar production environment. In addition, unified and centralized service management mechanism should be avoided as far as possible. For a specific service, appropriate language and tools should be selected according to the context

Microservice architecture mainly includes: service registration and discovery, service invocation, service fusing, load balancing, service degradation, service message queue, configuration center management, service gateway, service monitoring, full link tracking, automatic construction and deployment, and service timing task scheduling

SpringCloud = a one-stop solution for distributed microservice architecture, which is a collection of various microservice architecture landing technologies

Create parent project

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>seckill</artifactId>
<!--    Packaging method-->
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
<!--    Add module information-->
    <modules>
        <module>seckill-mail1</module>
        <module>skeckill-mail2</module>
<!--        <module>seckill-mail2</module>-->
    </modules>

<!--    Add version control-->
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <java.version>1.8</java.version>
        <spring-boot.version>2.4.0</spring-boot.version>
        <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
    </properties>

<!--    Put dependency into dependency management tab-->
    <dependencyManagement>
        <dependencies>
<!--            This dependency is spring boot Parent project-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

</project>

Maven uses the DependencyManagement element to provide a way to manage the dependent version number. Usually, you will see the DependencyManagement element in the parent POM at the top level of an organization or project, and use POM The DependencyManagement element in XML allows all to reference a dependency in a subproject without explicitly listing the version number
Maven will go up the parent-child hierarchy until it finds a project with the same dependency management element, and then it will use the version number specified in the dependency management element
The advantages of this are: if multiple subprojects reference the same dependency, you can avoid declaring a version number in each used subproject. In this way, when you want to upgrade or switch to another version, you only need to update in the top-level parent container instead of modifying in one subproject; In addition, if a sub project needs another version, you only need to declare version
Dependency management only declares dependencies and does not implement the introduction. Therefore, subprojects need to explicitly declare the dependencies that need to be used
If the dependency is not declared in the child project, it will not be inherited from the parent project. Only when the dependency is written in the child project and no specific version is specified, the item will be inherited in the parent project, and both version and scope are read from the parent pom
If the version number is specified in the subproject, the jar version specified in the subproject is used

Rest microservice engineering construction
1. Create module
2. Change pom file

server:
  port: 8001

3. Write YML

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-actuator</artifactId>
	</dependency>
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
	</dependency>
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid-spring-boot-starter</artifactId>
		<version>1.1.10<ersion>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>
</dependencies>

4. Main startup class

@SpringBootApplication
public class PaymentMain8001 {
	public static void main(String[] args) {
		SpringApplication.run(PaymentMain8001.class, args);
	}
}

5. Business class
① Create SQL table

create table payment (
	`id` bigint(20) not null auto_increment comment 'id',
	`serial` varchar(200) default '',
	primary key (`id`))
) engine = innodb auto_increment=1 default charset=utf8;

② Entity class
Subject class

@Data
@AllArgsConstructor
@NoArgsContructor
public class Payment implements Serializable {
	private Long id;
	private String serial;
}

Json encapsulation class CommonResult

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
	private Integer code;
	private String message;
	
	public CommonResult (Integer code, String message) {
		this(code, message, null);
	}
}

③dao
Interface PaymentDao

@Mapper
public interface PaymentDao {
	int create(Payment payment);
	Payment getPaymentById(@Param("id") Long id);
}

mybatis's mapping file paymentmapper xml
Path SRC \ main \ resources \ mapper \ paymentmapper xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="org.example.springcloud.dao.PaymentDao>
	<insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
		insert into payment(serial) values(#({serial}));
	</insert>

	<resultMap id="BaseResultMap" type="org.example.springcloud.entities.Payment">
		<id column="id" property="id" jdbcType="BIGINT"/>
		<id column="serial" property="serial" jdbcType="VARCHAR" />
	</resultMap>
	<select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
		select id, serial from payment where id=#{id}; 
	</select>
</mapper>

④Service

public interface PaymentService {
	int create (Payment payment);
	Payment getPaymentById(@Param("id") Long id);
}
@Service
public class PaymentServiceImpl implements PaymentService {
	@Resource 
	private PaymentDao paymentDao;

	@Override
	public int create(Payment payment) {
		return paymentDao.create(payment);
	}

	@Override
	public Payment getPaymentById(Long id) {
		return paymentDao.getPaymentById(id);
	}
}

⑤Controller

@RestController
@Slf4j
public class PaymentController {
	@Resource
	private PaymentService paymentService;

	@PostMapping("/payment/create")
	public CommonResult create(Payment payment) {
		int result = paymentService.create(payment);
		log.info("****Insert results" + result);
		if (result > 0) return new CommonResult(200, "Insert database succeeded", result);
		else return new CommonResult(444, "Insert database failed", null);
	}

	@GetMapping("/payment/get/{id}")
	public CommonResult getPaymentById(@PathVariable("id") Long id) {
		Payment payment = paymentService.getPaymentById(id);
		log.info("****Query results" + payment);
		
		if (payment != null) return new CommonResult(200, "query was successful", result);
		else return new CommonResult(444, "No corresponding record, query ID: " + id, null);
	}
}

RestTemplate provides a variety of convenient methods to access remote Http services. It is a simple and convenient template class to access restful services. It is the client template tool set provided by Spring to access Rest services
Official website address https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
Don't forget to add @ RequestBody annotation

@PostMapping("/payment/create")
public CommonResult create(@RequestBoby Payment payment) {
	int result = paymentService.create(payment);
}
@Configuration
public class ApplicationContextConfig {
	@Bean
	public RestTemplate getRestTemplate() {
		return new RestTemplate();
	}
}
@Slf4j
@RestController
public class OrderController {
	public static final String PAYMENT_URL = "http://localhost:8001";
	
	@Resource
	private RestTemplate restTemplate;

	@GetMapping("/consumer/payment/create")
	public CommonResult<Integer> create(Payment payment) {
		return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
	}

	@GetMapping("/consumer/payment/get/{id}")
	public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
		return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
	}
}

(url, requestMap, ResponseBean.class) these three parameters respectively represent the object type to which the REST request address, request parameters and HTTP response conversion are converted

Topics: Java Spring Cloud Microservices