Spring Cloud Micro Service Architecture From Getting Started to Getting Used - Calling Feign Between Services

One of the most important functions of micro-services is the call between services, which depend on each other.For example, e-commerce systems have order services and inventory services.When we buy a product, we need to generate orders and reduce inventory.Here we're going to use inter-service Feign calls.

Feign is a lightweight framework for HTTP request invocation, which calls Http requests with Java interface annotations instead of directly invoking them in Java by encapsulating HTTP request messages.

Next, we create two new module s, one app-order and one app-storage; app-order as the caller and app-storage as the callee.mybatis-plus is used as the data processing framework.Simplify code using lombok (idea needs to follow lombok plug-ins, otherwise errors will occur)

1. Create app-storage

1.1 Modify the pom.xml file under app-storage
<properties>
   <java.version>1.8</java.version>
   <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
</properties>

<dependencies>
   <dependency>
       <groupid>org.springframework.boot</groupid>
       <artifactid>spring-boot-starter-web</artifactid>
   </dependency>
    <!-- eureka-client -->
   <dependency>
       <groupid>org.springframework.cloud</groupid>
       <artifactid>spring-cloud-starter-netflix-eureka-client</artifactid>
   </dependency>
   <!-- feign -->
   <dependency>
       <groupid>org.springframework.cloud</groupid>
       <artifactid>spring-cloud-starter-openfeign</artifactid>
   </dependency>

   <!--    mybatis-plus    -->
   <dependency>
       <groupid>com.baomidou</groupid>
       <artifactid>mybatis-plus-boot-starter</artifactid>
       <version>3.3.1.tmp</version>
   </dependency>
   <dependency>
       <groupid>mysql</groupid>
       <artifactid>mysql-connector-java</artifactid>
       <scope>runtime</scope>
   </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>
       <exclusions>
           <exclusion>
               <groupid>org.junit.vintage</groupid>
               <artifactid>junit-vintage-engine</artifactid>
           </exclusion>
       </exclusions>
   </dependency>
</dependencies>

<dependencymanagement>
   <dependencies>
       <dependency>
           <groupid>org.springframework.cloud</groupid>
           <artifactid>spring-cloud-dependencies</artifactid>
           <version>${spring-cloud.version}</version>
           <type>pom</type>
           <scope>import</scope>
       </dependency>
   </dependencies>
</dependencymanagement>
1.2 Modify Configuration
# Set Port Number
server.port=9920
# Set Service Name
spring.application.name=app-storage
# Set up eureka
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.instance.instance-id=${spring.application.name}:${server.port}

# Data Source Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/storage?allowMultiQueries=true&amp;serverTimezone=GMT%2B8&amp;useSSL=false&amp;allowPublicKeyRetrieval=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
1.3 Create tables, prefabricate data
CREATE TABLE `tb_storage` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `commodity_code` varchar(255) DEFAULT NULL,
  `count` int(11) DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY (`commodity_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Prefabricated data

INSERT INTO `storage`(`id`, `commodity_code`, `count`) VALUES (1, 'product-1', 9999999);
1.4 Modify Startup Class
@SpringBootApplication
@EnableEurekaClient  // Turn on eureka client mode
@MapperScan("com.ipp.springcloud.appstorage.mapper") // mybatis scan
public class AppOrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(AppOrderApplication.class, args);
    }
}
1.5 Create the entity, mapper, service, controller corresponding to the storage table

You can use the mybatis-plus code generation plug-in to generate the above code. The length issue is not detailed here. See the git repository for more information.

1.6 Create a inventory reduction interface for app-order calls

controller

/**
     * Reduce Inventory
     * @param commodityCode Commodity Code
     * @param count Number
     * @return
     */
    @RequestMapping(path = "/deduct")
    public Boolean deduct(String commodityCode, Integer count) {
        storageService.deduct(commodityCode, count);
        return true;
    }

service

@Override
    public void deduct(String commodityCode, int count) {
        QueryWrapper<storage> wrapper = new QueryWrapper&lt;&gt;();
        wrapper.setEntity(new Storage().setCommodityCode(commodityCode));
        Storage storage = baseMapper.selectOne(wrapper);
        storage.setCount(storage.getCount() - count);
        baseMapper.updateById(storage);
    }

2. Create app-order

2.1 Modify the pom.xml file under app-order

Content is consistent with app-storage

2.2 Modify Configuration
# Set Port Number
server.port=9910
# Set Service Name
spring.application.name=app-order
# Set up eureka
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.instance.instance-id=${spring.application.name}:${server.port}

# Data Source Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/order?allowMultiQueries=true&amp;serverTimezone=GMT%2B8&amp;useSSL=false&amp;allowPublicKeyRetrieval=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
2.3 Creating tables
CREATE TABLE `tb_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(255) DEFAULT NULL,
  `commodity_code` varchar(255) DEFAULT NULL,
  `count` int(11) DEFAULT 0,
  `money` int(11) DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.4 Modify Startup Class
@SpringBootApplication
@EnableEurekaClient  // Turn on eureka client mode
@EnableFeignClients //Open feign request
@MapperScan("com.ipp.springcloud.apporder.mapper") // mybatis scan
public class AppOrderApplication {

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

}
2.5 Create the entity, mapper, service, controller corresponding to the table order

You can use the mybatis-plus code generation plug-in to generate the above code. The length issue is not detailed here. See the git repository for more information.

2.6 Create feign call interface
@FeignClient(name = "APP-STORAGE")
public interface StorageFeignService {
    /**
     * Reduce Inventory
     * @param commodityCode
     * @param count
     * @return
     */
    @GetMapping("storage/deduct")
    Boolean deduct(@RequestParam("commodityCode") String commodityCode, @RequestParam("count") Integer count);
}

The name in @FeignClient here says the service name of the app-storage service (that is, the service name registered with eureka)

The deduct method declared below corresponds to the deduct interface in the app-storage service

2.7 Create an interface for placing orders

controller

 @RequestMapping("/placeOrder/commit")
    public Boolean placeOrderCommit() {
        orderServiceImpl.placeOrder("1", "product-1", 1);
        return true;
    }

service

@Autowired
private StorageFeignService storageFeignService;

@Override
public void placeOrder(String userId, String commodityCode, Integer count) {
     BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
     Order order = new Order()
             .setUserId(userId)
             .setCommodityCode(commodityCode)
             .setCount(count)
             .setMoney(orderMoney);
     baseMapper.insert(order);
     storageFeignService.deduct(commodityCode, count);
}

3. Start service validation

Start server-eureka,app-storage,app-order in turn

4. Verify Interface

Access in Browser http://127.0.0.1:9910/order/placeOrder/commit To view the order table and the storage table, respectively.Are orders generated and inventory reduced </storage>

Keywords: Programming Spring Mybatis MySQL Java

Added by no_one on Sun, 22 Mar 2020 06:05:11 +0200