I Microservice architecture coding construction
1. Create parent project
2. Aggregate parent project name
3.Maven selected version
Note: maven selects version 3.5 or above
Remember: agreement > configuration > coding. Build the environment before coding
4. Character coding
5. Note validation activation
6. Select 8 for Java compiled version
7.File Type filtering
Can not filter, depending on personal habits
8. Parent project pom file optimization
1. Change the packaging method to pom
2. Delete src folder
3. Import version dependency
2021.6.17 latest test
<?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>com.chufeng.springcloud</groupId> <artifactId>mscloud2021</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.18.20</lombok.version> <mysql.version>8.0.24</mysql.version> <druid.version>1.2.4</druid.version> <mybatis.spring.boot.version>2.1.4</mybatis.spring.boot.version> </properties> <!-- unified management jar Package version --> <!-- After the sub module inherits, it provides the following functions: locking the version+son modlue Do not write groupId and version --> <dependencyManagement> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!--spring boot 2.2.2--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.10.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud Hoxton.SR11--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR11</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud alibaba 2.1.0.RELEASE--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.1.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <optional>true</optional> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <addResources>true</addResources> </configuration> </plugin> </plugins> </build> </project>
This label appears to represent the top-level parent container management
If the version number is specified in the parent class, the child class does not need to specify the version number when inheriting the parent class
The advantage of this is: if multiple subprojects refer to 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 without modifying 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, the declarations that need to be displayed in subprojects need dependencies.
- If the dependency is not declared in the child project, it will not be relayed 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 from 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.
4. In order to save time, select the button in the figure below, the test will become unavailable, and you can skip the test
5. After the parent project is created, execute mvn:install to publish the parent project to the warehouse to facilitate the inheritance of the child project
Tips: pay attention to sleeping on time, combine work and rest, and improve efficiency. See that the brothers here can continue to stick to it, come on
In order to eat instant noodles, you can add a sausage=-=
9. Construction of payment module
1. Cloud provider payment8001 micro service provider payment Module
How to build a microservice module?
- Build cloud provider payment8001 module
- Change pom
- Write yml
- Main start
- Business class
- test
Build cloud provider payment8001 sub module
Project structure
After the sub module is created, let's check the changes of the following parent pom
Here we can see that the sub module has been added, so it's no problem
Remember conventions > configuration > encoding
Change cloud provider payment8001pom file
<?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"> <parent> <artifactId>mscloud2021</artifactId> <groupId>com.chufeng.springcloud</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>cloud-provider-payment8001</artifactId> <dependencies> <!-- Graphical display--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Coordinate monitoring--> <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.2.4</version> </dependency> <!--mysql-connector-java--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--jdbc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
Write yml file
Note: the icon of the following leaves is the yml file
server: port: 8001 #Port number spring: application: name: cloud-payment-service #Microservice name datasource: type: com.alibaba.druid.pool.DruidDataSource # Current data source operation type driver-class-name: com.mysql.cj.jdbc.Driver # MySQL driver package com mysql. jdbc. Driver url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC username: root password: 388399 mybatis: mapperLocations: classpath:mapper/*.xml type-aliases-package: com.chufeng.springcloud.entities # Package of all Entity alias classes
Note: Password: the default password is 123456. If it is set, enter it. The meysql url of version 8.0 needs a time zone
Create main startup class
package com.chufeng.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PaymentMain8081 { public static void main(String[] args) { SpringApplication.run(PaymentMain8081.class,args); } }
Tip: the steps must be detailed without omission, otherwise it is easy to encounter pits. We must carefully think about the version conflicts of various jar packages, and the role of each setting of the configuration file. We will not check and ask, not only the form, but also learn to be refined 😊
1. Business
sql statement
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
Primary entity Payment
package com.chufeng.springcloud.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data//GetSet method @AllArgsConstructor//Argument constructor @NoArgsConstructor//Null parameter constructor public class Payment implements Serializable { private Long id; private String serial; }
Json package CommonResult
package com.chufeng.springcloud.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data//GetSet method @AllArgsConstructor//Argument constructor @NoArgsConstructor//Null parameter constructor public class CommonResult<T> {//Because the front and back ends are separated, the general return message uses T private Integer code;//Error code private String message;//Error message private T data;//data public CommonResult(Integer code, String message) { this(code,message,null); } }
dao interface
package com.chufeng.springcloud.dao; import com.chufeng.springcloud.entities.Payment; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @Mapper//mapper is recommended public interface PaymentDao { @Insert("insert into payment(serial) values(#{p.serial})") public int create(@Param("p") Payment payment); @Select("select * from payment where id=#{id}") public Payment getPaymentById(@Param("id")Long id); }
Note: I prefer to use annotation (annotation is convenient, disadvantage: annotation is a kind of strong coupling, which is not convenient to write complex sql), so I didn't write xml like Mr. Zhou Yang, but I also prepared an xml code for your convenience
xml file code
<?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="com.chufeng.springcloud.dao.PaymentDao"> <resultMap id="BaseResultMap" type="com.chufeng.springcloud.entities.Payment"> <id column="id" property="id" jdbcType="BIGINT"/> <result column="serial" property="serial" jdbcType="VARCHAR"/> </resultMap> <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id"> INSERT INTO payment(SERIAL) VALUES(#{serial}); </insert> <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap" > SELECT * FROM payment WHERE id=#{id}; </select> </mapper>
- resultMap: the attribute id of complex sql mapping is the method name of the interface, the type is the class address of the entity, the "id" tag indicates that the column is the primary key, the column is the column name of the database, the property is the attribute of the entity class, the JDBC type represents what type the column is in the database, and the "result" tag indicates a column
- insert: add parameterType: input type, parameter useGeneratedKeys: when set to true, it means that if the inserted table id takes the self incrementing column as the primary key, JDBC is allowed to support automatic generation of primary key, and the automatically generated primary key id can be returned. keyProperty: specifies which property is the primary key and receives the returned id
service interface
package com.chufeng.springcloud.service; import com.chufeng.springcloud.entities.Payment; public interface PaymentService { public int create(Payment payment); public Payment getPaymentById(Long id); }
service implementation class
package com.chufeng.springcloud.service.Impl; import com.chufeng.springcloud.dao.PaymentDao; import com.chufeng.springcloud.entities.Payment; import com.chufeng.springcloud.service.PaymentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; @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); } }
- If the mapper interface uses @ mapper annotation, an error will be reported when @ Autowired is used in the service layer injection. Therefore, here we use @ Resource in the service layer and @ Resource is thread safe
controller layer code
package com.chufeng.springcloud.controller; import com.chufeng.springcloud.entities.CommonResult; import com.chufeng.springcloud.entities.Payment; import com.chufeng.springcloud.service.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController//Represents the combination of two annotations: ResponseBody and Controller @Slf4j//Print log public class PaymentController { @Resource private PaymentService paymentService; //Because it is a front-end html5 project call, we use CommonResult to return the result @PostMapping(value = "/payment/create") public CommonResult create(Payment payment){ int result =paymentService.create(payment); //In enterprises, we all view the results through logs log.info("******Insert results"+result); //If the login fails, you should give a prompt to the front end to handle the interactive feedback if(result>0){ return new CommonResult(200,"Database inserted successfully",result); }else{ return new CommonResult(444,"Insert database failed",null); } } @GetMapping(value = "/payment/get/{id}") public CommonResult getPaymentById(@PathVariable("id") Long id){ Payment payment =paymentService.getPaymentById(id); //In enterprises, we all view the results through logs log.info("******Query results"+payment); //If the login fails, you should give a prompt to the front end to handle the interactive feedback if(payment!=null){ return new CommonResult(200,"query was successful",payment); }else{ return new CommonResult(444,"No corresponding record,query ID:"+id,null); } } }
test
The browser cannot directly support the test of post method, so we use postman next
query
add to
Self test passed
Note: at present, only one micro service has been started, so we can't see any effect
Summary:
- Create module
- Change pom
- Write YML
- Main start
- Business class
Tip: self study and self-discipline can lead to freedom
2. Hot deploy Devtools
3.cloud -consumer-order80 micro service consumer order Module
Continuous updating