Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Springboot+Dubbo to build distributed Micro Services

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Springboot+Dubbo to build distributed micro-services", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Springboot+Dubbo to build distributed micro-services.

First, let's take a picture.

Speaking of Dubbo, I believe everyone will be familiar with it! Alibaba's open source high-performance and excellent service framework enables applications to realize the output and input functions of services through high-performance RPC, and can be seamlessly integrated with the Spring framework.

Dubbo architecture diagram

Node role description:

Provider: the provider of the exposed service

Consumer: the service consumer that invokes remote services

Registry: the registry for service registration and discovery

Monitor: a monitoring center that counts the number and time of service calls

Container: service running container

Second, the realization train of thought

Today, we use the process of a user to select goods to place an order, split it into three business services: user center, merchandise center, order center, and use Springboot + Dubbo to achieve a small Demo!

The service interaction process is as follows:

This article mainly introduces the framework integration and development practice of Springboot and Dubbo, and the real business service split is a very complex process, which is much more complicated than the one we introduced. The three services mentioned above are just for project demonstration, so don't worry too much about why they should be split like this!

All right, let's cut the crap and let's do it!

1. Create 4 centos7 in the virtual machine, and install zookeeper on any one of them

two。 Build a micro-service project and write code

3. Deploy micro services on centos7

4. Remote service invocation test

III. Zookeeper installation

Before using Dubbo, we need a registry. At present, the registries that Dubbo can choose are zookeeper, Nacos, etc. It is generally recommended to use zookeeper!

First of all, before installing Zookeeper, you need to install and configure JDK, which uses Oracle Java8 SE.

Install JDK (already installed and can be ignored)

Yum-y install java-1.8.0-openjdk

View java installation

Java-version

After the JDK installation is complete, download and install Zookeeper

# create a zookeeper folder cd / usr mkdir zookeeper # download the zookeeper-3.4.14 version of wget http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.4.14/zookeeper-3.4.14.tar.gz # extract tar-zxvf zookeeper-3.4.14.tar.gz

Create data and log directories

# create a directory for data and log storage cd / usr/zookeeper/ mkdir data mkdir log # back up the zoo_sample.cfg under conf and rename it to zoo.cfg cd conf/ cp zoo_sample.cfg zoo.cfg

Configure zookeeper

# Editing zoo.cfg file vim zoo.cfg

Start Zookeeper

# enter Zookeeper's bin directory cd zookeeper/zookeeper-3.4.14/bin # launch Zookeeper. / zkServer.sh start # query Zookeeper status. / zkServer.sh status # turn off Zookeeper status. / zkServer.sh stop

The following message appears, indicating that the startup is successful!

IV. Project introduction

Springboot version: 2.1.1.RELEASE

Zookeeper version: 3.4.14

Dubbo version: 2.7.3

Mybtais-plus version: 3.0.6

Database: mysql-8

Build tool: maven

Service module: user center, commodity center, order center

Fifth, code practice

5.1. Initialize the database

First, on the mysql client, create three databases: dianshang-user, dianshang-platform, and dianshang-business.

In the dianshang-user database, create the user table tb_user and initialize the data

In the dianshang-platform database, create the commodity table tb_product and initialize the data

In the dianshang-platform database, create the order table tb_order and the order details table tb_order_detail

5.2. Create a project

After the database table is designed, create a Springboot project named dianshang under IDEA.

The final directory is as follows:

Description of directory structure:

Dianshang-common: mainly stores some common tool libraries, all services can be relied on to use

Dianshang-business: order center, where the api module mainly provides dubbo service exposure interface, and the provider module is a springboot project that provides service processing operations

Dianshang-user: user center, where api module and provider module are similar in design

Dianshang-platform: merchandise center, where api module and provider module are similar in design

Add dubbo and zookeeper clients to the parent class pom file, and all dependent projects can be used.

Org.projectlombok lombok 1.18.4 provided org.apache.dubbo dubbo-spring-boot-starter 2.7.3 org.apache.zookeeper zookeeper 3.4.13 org.slf4j slf4j-api org.slf4j slf4j-log4j12 Log4j log4j org.apache.curator curator-framework 4.2.0 org.apache.curator curator-recipes 4.2.0

Warm Tip: Xiaobian found a pit when building the environment. The version of zookeeper that the project depends on should be consistent with the version of the server. For example, in this case, the version of the zookeeper server is 3.4.14, so when relying on the zookeeper file library, try to keep it consistent. If you rely on the 3.5.x version of zookeeper, the project will report all kinds of ghosts and ghosts when it starts!

5.3. Create a user-centric project

In IDEA, create a dianshang-user submodule and rely on the dianshang-common module

Org.project.demo dianshang-common 1.0.0

At the same time, create dianshang-user-provider and dianshang-user-api modules.

Dianshang-user-api: mainly provides interface exposure to other services

Dianshang-user-provider: similar to a web project, it is mainly responsible for the crud of basic business and relies on dianshang-user-api module.

5.3.1. Configure dubbo service

Configure the dubbo service in the application.yml file of dianshang-user-provider as follows:

# user center service port server: port: 8080 # data source configuration spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: "jdbc:mysql://localhost:3306/dianshang-user" username: root password: 111111 # dubbo configuration dubbo: scan: # package name write base-packages: org.project.dianshang.user according to your actual situation Protocol: port: 20880 name: dubbo registry: # zookeeper registry address address: zookeeper://192.168.0.107:2181

5.3.2. Write service exposure interfaces and implementation classes

In the dianshang-user-api module, create a UserApi interface and return the parameter object UserVo!

Public interface UserApi {/ * query user information * @ param userId * @ return * / UserVo findUserById (String userId);}

For UserVo, serialization is required, as follows:

@ Data @ EqualsAndHashCode (callSuper = false) @ Accessors (chain = true) public class UserVo implements Serializable {private static final long serialVersionUID = 1L; / * * user ID * / private String userId; / * * user Chinese name * / private String userName;}

In the dianshang-user-provider module, write the UserApi interface implementation class as follows:

@ Service (interfaceClass = UserApi.class) @ Component public class UserProvider implements UserApi {@ Autowired private UserService userService; @ Override public UserVo findUserById (String userId) {QueryWrapper queryWrapper = new QueryWrapper (); queryWrapper.eq ("user_id", userId); User source = userService.getOne (queryWrapper); if (source! = null) {UserVo vo = new UserVo (); BeanUtils.copyProperties (source,vo) Return vo;} return null;}}

The annotation @ Service refers to the comments under org.apache.dubbo.config.annotation.Service, not those under Spring!

Then, we continue to create the commodity center project!

5.4. Create a commodity center project

Similar to the user-centric project, in IDEA, you create a dianshang-platform submodule and rely on the dianshang-common module

Org.project.demo dianshang-common 1.0.0

At the same time, create dianshang-platform-provider and dianshang-platform-api modules.

Dianshang-platform-api: mainly provides interface exposure to other services

Dianshang-platform-provider: similar to a web project, it is mainly responsible for the crud of basic business and relies on dianshang-platform-api module.

5.4.1. Configure dubbo service

Configure the dubbo service in the application.yml file of dianshang-platform-provider as follows:

# user center service port server: port: 8081 # data source configuration spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: "jdbc:mysql://localhost:3306/dianshang-platform" username: root password: 111111 # dubbo configuration dubbo: scan: # package name write base-packages: org.project.dianshang.platform according to your actual situation Protocol: port: 20881 name: dubbo registry: # zookeeper registry address address: zookeeper://192.168.0.107:2181

5.4.2. Write service exposure interfaces and implementation classes

In the dianshang-platform-api module, create a ProductApi interface and return the parameter object ProductVo!

Public interface ProductApi {/ * query commodity information * @ param productId * @ return * / ProductVo queryProductInfoById (String productId) through commodity ID

For ProductVo, serialization is required, as follows:

@ Data @ EqualsAndHashCode (callSuper = false) @ Accessors (chain = true) public class ProductVo implements Serializable {private static final long serialVersionUID = 1L; / * Commodity ID*/ private String productId; / * Commodity name * / private String productName; / * * Commodity Price * / private BigDecimal productPrice;}

In the dianshang-platform-provider module, write the ProductApi interface implementation class as follows:

@ Service (interfaceClass = ProductApi.class) @ Component public class ProductProvider implements ProductApi {@ Autowired private ProductService productService; @ Override public ProductVo queryProductInfoById (String productId) {/ / query information Product source = productService.getById (productId) through commodity ID; if (source! = null) {ProductVo vo = new ProductVo (); BeanUtils.copyProperties (source,vo); return vo } return null;}}

Then, let's continue to create the order center project!

5.5. Create an order center project

Similar to the merchandise center project, in IDEA, you create a dianshang-business submodule and rely on the dianshang-common module

Org.project.demo dianshang-common 1.0.0

At the same time, create dianshang-business-provider and dianshang-business-api modules.

Dianshang-business-api: mainly provides interface exposure to other services

Dianshang-business-provider: similar to a web project, it is mainly responsible for the crud of basic business and relies on dianshang-business-api module.

5.5.1. Configure dubbo service

Configure the dubbo service in the application.yml file of dianshang-business-provider as follows:

# user center service port server: port: 8082 # data source configuration spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: "jdbc:mysql://localhost:3306/dianshang-business" username: root password: 111111 # dubbo configuration dubbo: scan: # package name write base-packages: org.project.dianshang.business according to your actual situation Protocol: port: 20882 name: dubbo registry: # zookeeper registry address address: zookeeper://192.168.0.107:2181

5.5.2. Write service exposure interfaces and implementation classes

In the dianshang-business-api module, create an OrderApi interface and return the parameter object OrderVo!

Public interface OrderApi {/ * query user order information * @ param userId * @ return * / List queryOrderByUserId (String userId) through user ID;}

For OrderVo, serialization is required, as follows:

@ Data @ EqualsAndHashCode (callSuper = false) @ Accessors (chain = true) public class OrderVo implements Serializable {private static final long serialVersionUID = 1L; / * order ID*/ private String orderId; / * order No. * / private String orderNo; / * * order amount * / private BigDecimal orderPrice; / * * order time * / private Date orderTime;}

In the dianshang-business-provider module, write the OrderApi interface implementation class as follows:

@ Service (interfaceClass = OrderApi.class) @ Component public class OrderProvider implements OrderApi {@ Autowired private OrderService orderService; @ Override public List queryOrderByUserId (String userId) {QueryWrapper queryWrapper = new QueryWrapper (); queryWrapper.eq ("user_id", userId); List sourceList = orderService.list (queryWrapper); if (! CollectionUtils.isEmpty (sourceList)) {List voList = new ArrayList () For (Order order: sourceList) {OrderVo vo = new OrderVo (); BeanUtils.copyProperties (order, vo); voList.add (vo);} return voList;} return null;}}

So far, the service exposure interfaces for 3 projects have been developed! Next let's write how to make a remote call!

5.6. Remote call

5.6.1, write and create order service

In the dianshang-business-provider module, you rely on dianshang-business-api and dianshang-user-api before writing the interface to create an order, as follows:

Org.project.demo dianshang-platform-api 1.0.0 org.project.demo dianshang-user-api 1.0.0

In the dianshang-business-provider module, write the create order service as follows:

@ RestController @ RequestMapping ("/ order") public class OrderController {@ Autowired private OrderService orderService; @ Autowired private OrderDetailService orderDetailService; @ Reference (check = false) private ProductApi productApi; @ Reference (check = false) private UserApi userApi / * * New * / @ JwtIgnore @ RequestMapping (value = "/ add") public boolean add (String productId,String userId) {LocalAssert.isStringEmpty (productId, "Product Id cannot be empty"); LocalAssert.isStringEmpty (userId, "user Id cannot be empty"); ProductVo productVo = productApi.queryProductInfoById (productId); LocalAssert.isObjectEmpty (productVo, "Product information not found") UserVo userVo = userApi.findUserById (userId); LocalAssert.isObjectEmpty (userVo, "user information not found"); Order order = new Order (); order.setOrderId (IdGenerator.uuid ()); order.setOrderNo (System.currentTimeMillis () + "); order.setOrderPrice (productVo.getProductPrice ()); order.setUserId (userId); order.setOrderTime (new Date ()); orderService.save (order) OrderDetail orderDetail = new OrderDetail (); orderDetail.setOrderDetailId (IdGenerator.uuid ()); orderDetail.setOrderId (order.getOrderId ()); orderDetail.setProductId (productId); orderDetail.setSort (1); orderDetailService.save (orderDetail); return true;}}

The @ Reference annotation belongs to the annotation under org.apache.dubbo.config.annotation.Reference and indicates remote dependency on the service.

Parameter check= false means that when starting the service, no remote service status check is done. The purpose of this setting is to prevent the current service from not starting. For example, the user center project does not start successfully, but the order center depends on the user center. If check=true, the order center will report an error when it starts!

5.6.2. Write users to query their own order information

Similarly, in the dianshang-user-provider module, before writing an API for users to query their own order information, rely on dianshang-business-api and dianshang-user-api, as follows:

Org.project.demo dianshang-business-api 1.0.0 org.project.demo dianshang-user-api 1.0.0

In the dianshang-user-provider module, write an API for users to query their own order information, as follows:

@ RestController @ RequestMapping ("/ user") public class UserController {@ Reference (check = false) private OrderApi orderApi; / * query order information through user ID, * @ param userId * @ return * / @ RequestMapping ("/ list") public List queryOrderByUserId (String userId) {return orderApi.queryOrderByUserId (userId);}}

At this point, the remote service invocation is complete!

VI. Service testing

Before deploying the project on the server, let's test it locally to see if all the services are available.

Start user Center dianshang-user-provider

Continue to start the commodity center dianshang-platform-provider

Then start the order center dianshang-business-provider

Finally, let's test whether the service interface is the result we expected.

Open the browser, enter the http://127.0.0.1:8082/order/add?productId=1&userId=1 test to create an order interface, and the results of the page display normally!

Let's take a look at the database. Is the order generated?

Ok! See very clearly, the data has gone in, there is no problem!

Let's test the order query interface in the user center, enter http://127.0.0.1:8080/user/list?userId=1, and the page runs as follows!

At this point, the local service test basically passed!

VII. Server deployment

In the above, we introduced the construction, development, and testing of the service, so how can it be deployed on the server side?

First of all, modify the application.yml file of each project, change the data source address and dubbo registry address to the address that can be connected online, and then use the maven tool in the dianshang directory to package the whole project by executing the following command!

Mvn clean install

Packaging can also be performed through the maven configuration clean install command in the IDEA environment.

Copy the dianshang-user-provider.jar, dianshang-platform-provider.jar, dianshang-business-provider.jar in the target directory of each project.

Upload to the corresponding server directory, this server uses CentOS7, a total of 4 servers, of which one deploys zookeeper and the other three deploys three micro-service projects.

Log in to the server and enter the following command to make sure that JDK has been installed!

Java-version

Turn off the firewalls of all servers and release port access!

# turn off the firewall systemctl stop firewalld.service # do not boot and start systemctl disable firewalld.service

Start the user center service and output the log information to service.log (virtual machine ip:192.168.0.108)

Nohup java-jar dianshang-user-provider.jar > service.log 2 > & 1 &

Start the commodity center service and output the log information to service.log (virtual machine ip:192.168.0.107)

Nohup java-jar dianshang-platform-provider.jar > service.log 2 > & 1 &

Start the order center service and output the log information to service.log (virtual machine ip:192.168.0.109)

Nohup java-jar dianshang-business-provider.jar > service.log 2 > & 1 &

Open the browser, enter the http://192.168.0.109:8082/order/add?productId=1&userId=1 test to create an order interface, and the results of the page display normally!

Let's test the order query interface in the user center, enter http://192.168.0.108:8080/user/list?userId=1, and the page runs as follows!

It is clear that two pieces of information have been output, the second order is generated on the test environment server, and the first is generated in the local development environment.

At this point, the server deployment is basically complete!

If it is a production environment, you may need multiple zookeeper to ensure high availability, at least 2 servers to deploy business services, and routing through load balancer!

At this point, I believe you have a deeper understanding of "how to use Springboot+Dubbo to build distributed micro-services". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report