Microservice scenario building (simulation)

1. Create parent project In microservices, you need to create multiple projects at the same time. First, you need to cre...
2.1 create Module
2.2. Preparation of configuration file
2.3. Writing code
2.4. Start and test
3.1. Create project
3.2. Coding
3.3. Start up test:
4. Thinking

1. Create parent project

In microservices, you need to create multiple projects at the same time. First, you need to create a parent project. Subsequent projects take this project as the parent and use Maven's aggregation and inheritance. Uniformly manage the version and configuration of subprojects
pom.xml 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"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>SpringCloudTest</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath/> </parent> <properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR1</spring-cloud.version> <mapper.starter.version>2.1.5</mapper.starter.version> <mysql.version>8.0.23</mysql.version> </properties> <dependencyManagement> <dependencies> <!-- springCloud --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>$</version> <type>pom</type> <scope>import</scope> </dependency> <!-- currency Mapper starter --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>$</version> </dependency> <!-- mysql drive --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>$</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

Note: the versions of spring cloud and spring boot correspond to greenwich version, and the cloud corresponds to spring boot 2.1.x
Note: aggregate parent project < packaging > POM < / packaging >
Most of the dependent versions to be used have been managed here to facilitate subsequent use

2. Service providers

We will create a new project to provide external services for querying users.

2.1 create Module

Select springcloudtest to create a sub project:
pom.xml 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>lxs-springcloud</artifactId> <groupId>com.lxs</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>user-service</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- currency Mapper starter --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> </dependency> <!-- mysql drive --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> </project>

Project structure:

2.2. Preparation of configuration file

Create the user service \ SRC \ main \ resources \ application.yml property file. Here, we use yaml syntax instead of properties:

server: port: 9091 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: da5201314 url: jdbc:mysql://localhost:3306/springboot mybatis: type-aliases-package: com.lxs.bean

Use the Mysql graphical interface tool to import the springcloud.sql script

DROP TABLE IF EXISTS `tb_user`; CREATE TABLE `tb_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, `age` int(11) DEFAULT NULL, `sex` int(11) DEFAULT NULL, `birthday` date DEFAULT NULL, `created` date DEFAULT NULL, `updated` date DEFAULT NULL, `note` varchar(2000) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; /*Data for the table `tb_user` */ insert into `tb_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`created`,`updated`,`note`) values (1,'zhangsan','1','Zhang San a',18,1,'2019-02-27','2019-02-27','2019-02-27','I'm learning Java...'), (2,'lisi','1','Li Si ab',18,1,'2019-02-27','2019-02-27','2019-02-27','I'm learning Java...'), (3,'wangwu','1','Wang Wu abc',18,1,'2019-02-27','2019-02-27','2019-02-27','I'm learning Java...'), (4,'fanbingbing','1','Fan Bingbing aa',18,2,'2019-02-27','2019-02-27','2019-02-27','I'm learning Java...'), (5,'guodegang','1','Guo Degang bb',18,1,'2019-02-27','2019-02-27','2019-02-27','I'm learning Java...'), (6,NULL,NULL,'Zhou Xingchi cc',18,NULL,'2021-06-01','2021-06-01',NULL,NULL), (7,'lqlql',NULL,'La La La',NULL,NULL,NULL,NULL,NULL,NULL);

2.3. Writing code

Startup class

@SpringBootApplication @MapperScan("com.lxs.dao") public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class,args); } }

Entity class

@Data @Table(name = "tb_user") public class User{ // id @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // user name private String userName; // password private String password; // full name private String name; // Age private Integer age; // Gender, 1 male, 2 female private Integer sex; // date of birth private Date birthday; // Creation time private Date created; // Update time private Date updated; // remarks private String note;

UserMapper

import com.lxs.bean.User; import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { }

service:

@Service public class UserService { @Autowired(required = false) private UserMapper userMapper; public User queryById(Long id) { return this.userMapper.selectByPrimaryKey(id); } }

controller
Provide REST style web Services externally, and query users according to their id

@RestController @RequestMapping("/user") public class UserController { @Autowired(required = false) private UserService userService; @GetMapping("/") public User queryById(@PathVariable Long id){ return userService.queryById(id); } }

Project structure after completing the above code

2.4. Start and test

Start project, access http://localhost:9091/user/7

3. Service callers

3.1. Create project

Similar to the above, when creating a project, it should be noted that we call the function of user service, so we don't need to rely on Mybatis
pom:

<?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>SpringCloudTest</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>consumer-demo</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>

application.yml:

server: port: 9093 spring: application: name: consumer

The project structure is as follows:

3.2. Coding

Starter:

@SpringBootApplication public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }

Spring provides a RestTemplate template tool class, encapsulates the HTTP based client, and implements the serialization and deserialization of objects and json, which is very convenient. RestTemplate does not limit the HTTP client type, but abstracts it. At present, there are three common types
Hold:

  • HTTPClient
  • OkHTTP
  • JDK native URLConnection (default)

Entity class

@Data public class User { private Long id; // user name private String userName; // password private String password; // full name private String name; // Age private Integer age; // Gender, 1 male, 2 female private Integer sex; // date of birth private Date birthday; // Creation time private Date created; // Update time private Date updated; // remarks private String note;

controller

@RestController @RequestMapping("/consumer") public class ConsumerController { @Autowired(required = false) private RestTemplate restTemplate; @GetMapping("/") public User queryById(@PathVariable Long id){ String url = "HTTP://localhost:9091/user/"+id; return restTemplate.getForObject(url, User.class); } }

3.3. Start up test:

We visit: http://localhost:9093/consume/7

4. Thinking

Briefly review what we just wrote:

  • User service: provides an external interface for querying users
  • Consumer Demo: accessed through RestTemplate http://locahost:9091/user/ interface to query user data

What's the problem?

  • In the consumer, we hard code the url address into the code, which is not convenient for later maintenance
  • The consumer needs to remember the address of the user service. If there is a change, it may not be notified, and the address will become invalid
  • The consumer does not know the status of the user service, nor does it know that the service is down
  • There is only one user service, which is not highly available
  • Even if user services form clusters, consumer s need to achieve load balancing by themselves

In fact, the problems mentioned above are the problems that distributed services must face:

Service management

  • How to automatically register and discover
  • How to realize status supervision
  • How to implement dynamic routing

How do services achieve load balancing
How does the service solve the problem of disaster recovery
How to realize unified configuration of services
All the above questions will be answered in spring cloud

19 November 2021, 18:42 | Views: 5613

Add new comment

For adding a comment, please log in
or create account

0 comments