What are microservices? A series will be seen at a glance!
2. Teach you how to build a SpringCloud project (2) Producers and consumers
3. Teach you how to build a SpringCloud project (3) Integrate the Eureka service registration center
4. Teach you how to build the SpringCloud project (4) Eureka cluster version construction
5. Teach you how to build the SpringCloud project (5) Build the producer cluster version
6. Teach you how to build a SpringCloud project (6) Eureka realizes service discovery
7. Teach you how to build a SpringCloud project (7) Integrate the Consul service registration center
8. Teach you how to build a SpringCloud project (8) Integrated Ribbon load balancer
9. Teach you how to build a SpringCloud project (9) Integrate OpenFeign service interface calls
10. Teach you how to build a SpringCloud project (10) Integrate Hystrix service downgrade
11. Teach you to build a SpringCloud project (11) Integrating Hystrix's service fuse
13. Teach you how to build a SpringCloud project (13) Integrate a new generation of Gateway
15. Teach you how to build a SpringCloud project (15) Integrated Bus message bus
16. Teach you how to build a SpringCloud project (16) Integrated Stream message driver
17. Teach you how to build a SpringCloud project (17) Integrating Sleuth distributed link tracking
Continue to update, welcome to like and follow!
Let’s continue with the previous article. In the previous article, we completed the construction of the general project and entity microservices. In this article, we will continue to build producers and consumers. We can understand that the producer is our server. , is the business logic interface we write in code, and the consumer is our user, who calls the interface of our server through the app or web to obtain information. Then we will build directly below and learn from the project.
We first build a service dedicated to our payment business, so that other services can call and use it. Payment Services is one such producer.
1. Create a new producer
Select our parent project and click New, then click Module, as shown below:
Click Next.
Continue to Next, then click Finish.
Modify the pom.xml file and add dependencies. The specific version is managed in the general project, and other versions can also be used in this project. Note the package that imports the entity classes.
<?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>mcroservice</artifactId>
<groupId>com.study.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudprovidepayment</artifactId>
<dependencies>
<-- 引入实体的包-->
<dependency>
<groupId>com.study.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<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</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>
Create a new application.yml configuration file under the resources file
server:
port: 8001 #服务端口
#spring相关配置
spring:
application:
name: mcroservice-payment #服务名
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #数据库驱动包
url: jdbc:mysql://localhost:3306/db01?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password: roo
#mybatis:配置
mybatis:
mapperLocations: classpath:dao/*.xml
type-aliases-package: com.buba.springcloud.pojo # 所有pojo别名类所在包
write startup class
package com.buba.springclould;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
public class PayMentMain {
public static void main(String[] args) {
SpringApplication.run(PayMentMain.class,args);
}
}
Let's start writing business, which is a three-tier structure, as shown in the figure below:
PaymentDao.java code
package com.buba.springclould.dao;
import com.buba.springcloud.pojo.Payment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface PaymentDao {
int create(Payment payment);
Payment queryById(@Param("id")long id);
}
PaymentService.java代码
package com.buba.springclould.service;
import com.buba.springcloud.pojo.Payment;
import org.apache.ibatis.annotations.Param;
public interface PaymentService {
int create(Payment payment);
Payment queryById(@Param("id")long id);
}
PaymentImple.java code
package com.buba.springclould.service;
import com.buba.springcloud.pojo.Payment;
import com.buba.springclould.dao.PaymentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PaymentImple implements PaymentService {
@Autowired
PaymentDao paymentDao;
@Override
public int create(Payment payment) {
return paymentDao.create(payment);
}
@Override
public Payment queryById(long id) {
return paymentDao.queryById(id);
}
}
PaymentControler.java code
package com.buba.springclould.controller;
import com.buba.springcloud.pojo.CommonResult;
import com.buba.springcloud.pojo.Payment;
import com.buba.springclould.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/*
* 提供restful服务 供其他服务调用
*
* */
@RestController
@Slf4j
public class PaymentControler {
@Autowired
private PaymentService paymentService;
@PostMapping("/payment/create")
public CommonResult create(@RequestBody Payment dept){
int i = paymentService.create(dept);
log.info("***************插入成功*******"+i);
if(i>0){
return new CommonResult(200,"插入数据库成功"+serverPort,i);
}else{
return new CommonResult(444,"插入数据库失败",null);
}
}
@GetMapping("/payment/get/{id}")
public CommonResult queryById(@PathVariable("id") Long id){
Payment payment = paymentService.queryById(id);
log.info("***************查询成功*********"+payment);
if(payment!=null){
return new CommonResult(200,"查询成功"+serverPort,payment);
}else{
return new CommonResult(444,"查询失败",null);
}
}
}
Create a new PaymentDao.xml file under the resources\dao\ folder, and map it with PaymentDao. Here, pay attention to creating an xml file with a recognizable configuration for spring, and no error will be reported saying that the method cannot be found. As shown below:
Create a new PaymentDao.xml file, as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dqueryByidtd/mybatis-3-mapper.dtd">
<mapper namespace="com.buba.springclould.dao.PaymentDao">
<resultMap id="BaseResultMap" type="com.buba.springcloud.pojo.Payment">
<id column="id" property="id" jdbcType="BIGINT"/>
<id column="serial" property="serial" jdbcType="VARCHAR"/>
</resultMap>
<insert id="create" parameterType="com.buba.springcloud.pojo.Payment" useGeneratedKeys="true" keyProperty="id">
insert into payment (serial) values (#{serial});
</insert>
<select id="queryById" resultType="com.buba.springcloud.pojo.Payment" parameterType="Long" resultMap="BaseResultMap">
select * from payment where id = #{id};
</select>
</mapper>
2. Create a new consumer service
We have finished building the server project (producer) of the order, and then we start to build the client project (consumer) of the order. Select our parent project and click New, then click Module, as shown below:
Click Next and fill in the project name.
Continue to Next, confirm the project name, and click Finish to complete the creation of the order service project.
Start configuring and modifying the pom.xml file to add dependencies. The specific version is managed in the general project, and other versions can also be used in this project. Note the package that imports the entity classes.
<?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>
<groupId>com.study.springcloud</groupId>
<artifactId>mcroservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-consumer-order</artifactId>
<dependencies>
<dependency>
<-- 引入实体的包-->
<groupId>com.study.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<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.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>
<dependency>
<groupId>com.study.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
Create a new application.yml configuration file under the resources file
server:
port: 80
spring:
application:
name: mcroservice-order #服务名
write startup class
package com.buba.springclould.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
public class OrderMain {
public static void main(String[] args) {
SpringApplication.run(OrderMain.class,args);
}
}
Create a new RestTemplate configuration class and inject it into the ioc container in Spring
For the call between services here, we use RestTemplate. RestTemplate provides a variety of convenient methods for accessing remote Http services. It is a simple and convenient template class for accessing restful services. It is a client template for accessing Rest services provided by spring. Toolset.
package com.buba.springclould.order.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
Write the consumer's business call interface
package com.buba.springclould.order.controller;
import com.buba.springcloud.pojo.CommonResult;
import com.buba.springcloud.pojo.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@Slf4j
public class OrderController {
//调用支付订单服务端的ip+端口号
public static final String PAYMENT_URL = "http://localhost:8001";
@Autowired
private RestTemplate restTemplate;
//创建支付订单的接口
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment, CommonResult.class);
}
//获取id获取支付订单
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
3. Inter-service call test
The producer and consumer are set up. Then let's test now to see if the payment consumer can successfully call the payment producer. Start two projects separately. First, check whether the producer’s service can be accessed, the port is 8001, as shown in the figure below, it can be accessed successfully, indicating that the producer’s service is no problem.
The port of our consumer is configured as 80, and the port can be omitted for access, and directly enter: http://localhost/consumer/payment/get/1 to access. Successfully obtained the payment order with id 1.
At this point, our simple construction of springcloud is successful. Isn't it so easy!
Then we will continue to learn. Our next article will build a payment server cluster and integrate eureka service registration and discovery. Continue to follow and like. We continue to update.