SpringCloud Study Notes 02-Service Providers and Service Consumers


foreword

本文要记录的大概内容:

The above has a simple understanding and understanding of microservices. This article will briefly introduce Spring Cloud and conduct a simple introductory study of Spring Cloud through a simple case.

Simulation scene:

快速搭建服务提供者与服务消费者并完成两个服务之间的交互。以电影院购票为例:用户通过电影微服务系统
(服务消费者)购票,电影微服务需要调用用户微服务(服务提供者)查询用户相关信息,账户余额、是否符
合购票标准等。

insert image description here


提示:以下是本篇文章正文内容,下面案例可供参考

1. Introduction to Spring Cloud?

SpringCloud is built on the basis of SpringBoot, a tool set for quickly building a common pattern of distributed systems.
Applications developed using Spring Cloud are very suitable for deployment on Docker and PaaS, so they are also called cloud native applications. Cloud native (Cloud Native) can be understood as a software architecture for the cloud environment.

2. Features of Spring Cloud

  1. Convention over / over configuration
  2. Suitable for various environments. It can be developed and deployed on PC Server or various cloud environments (such as Alibaba Cloud, Tencent Cloud, AWS, etc.)
  3. Hide the complexity of components and provide declarative, XML-free configuration
  4. Out-of-the-box, quick setup and start
  5. Lightweight components. Most of the components integrated by Spring Cloud are relatively lightweight, such as Eureka, Zuul, etc. are all lightweight implementations in their respective fields
  6. Rich components and complete functions. Spring Cloud provides very complete support for microservice architecture, such as: configuration management, service discovery, circuit breaker, microservice gateway, etc.
  7. The selection is neutral and rich. For example, Spring Cloud supports service discovery using Eureka, ZooKeeper or Consul, etc.
  8. flexible. The components of Spring Cloud are decoupled, and developers can flexibly choose technology options as needed

3. Prerequisites for actual combat

1. Technical reserve

  • SpringBoot

     SpringCloud是基于SpringBoot构建的,因此它延续了SpringBoot的锲约模式以及开发方式
    
  • Development language

     SpringCloud是一个基于Java语言的工具套件,所以学习它需要一定的Java基础。Spring Cloud
     支持使用Scala、Groovy等语言进行开发。
    

2. Development tools

  • JDK

     JDK版本需要大于等于1.8
    
  • IDE

     使用eclipse、idea、或者Spring Tool Suite均可
    
  • Maven

     maven的版本应该选择大于3.3.X及以上
    

4. Write service consumers and providers

1. Write a service provider

Write a user microservice as a service provider, function: query personnel related information through the personnel number. The service uses Mybatis as the persistence layer framework and Mysql as the database.

1. Build the project

In addition to manually writing Class, yml, and xml to build projects, the commonly used methods are as follows:

  • through the web

     访问 https://start.spring.io/如下图:可以选择开发语言、版本、填写
     项目的相关信息
    

insert image description here

  • Through the development tool (this article takes IDEA as an example)
    1. Open the editor, click File–>New–>Project in the navigation bar, and select Spring Initializr as shown below:
    insert image description here
    项目属性说明

     Name:更友好的项目名,默认同Artifact保持一致
     Location:项目存储位置
     Language:开发语言
     Type:类型,项目管理工具
     Group:项目组织的唯一标识符
     Artifact:项目名称
     Pacjage name:包名,默认为Group+Artifact,可以手动更改。表示的main/java/目录下的包名
     Project SDK:项目使用的工具包
     Java:语言版本
     Packing:打包方式
    

2. Select Next–> as shown in the figure below, select the SpringBoot version and select project dependencies as needed, and the dependency package I selected is on the right (Spring Boot DevTools provides fast application restart, real-time loading and configuration; Spring Web uses Spring MVC to build Web Applications, including RESTful applications and some common annotations such as: @Controller, @RestController; MySQL Driver provides JDBC and R2DBC drivers for MySQ; JDBC API provides APIs for defining how clients connect, query databases, and database connections; MyBatis Framework is data Persistence framework; dependencies not selected when creating a project can be flexibly configured in pom.xml if used in the project)
注意:1. 选择了MyBatis Framework其实就可以不用选JDBC API的依赖了 2. 需要配置好maven,不然依赖包会下载失败
insert image description here
3. Click Finish, the project is created, open the pom file and report an error, as shown below:
insert image description here

Solution : Manually add the version number

  • Via the command line tool Spring Boot CLI

2. Write configuration files

The application.properties will be generated by default when creating a project, but it is recommended to use the yml file as the configuration file (high readability, but only one of the two can be left), and my configuration is as follows:

server:
  port: 8060
  servlet:
    context-path: "/api"
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: ******
    password: ******

3. Write api, service and mapper

api接口层:

package com.example.user.api;

import com.example.user.dto.UserDto;
import com.example.user.service.UserService;
import com.example.user.util.ResponseMsg;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/userApi")
public class UserApi {
    
    

    @Autowired
    private UserService userServce;

    @GetMapping("/getUserMsgById/{id}")
    public ResponseMsg<UserDto> getUserMsg(@PathVariable("id") Integer id){
    
    
        UserDto user = userServce.getUserMsgById(id);
        return ResponseMsg.success(user);

    }
}

Service层(分为接口和实现类,这里只写实现类):

package com.example.user.service.impl;

import com.example.user.dto.UserDto;
import com.example.user.entity.User;
import com.example.user.mapper.UserMapper;
import com.example.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDto getUserMsgById(Integer id) {
    
    
        User user = userMapper.queryById(id);
        UserDto userDto = null;
        if(user != null){
    
    
            userDto = new UserDto();
            BeanUtils.copyProperties(user,userDto);
        }
        return userDto;
    }
}

数据层:

package com.example.user.mapper;

import com.example.user.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {
    
    
    User queryById(Integer id);
}

<?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.example.user.mapper.UserMapper">
    <select id="queryById" parameterType="java.lang.Integer" resultType="com.example.user.entity.User">
        select *
        from t_user
        where id = #{id}
    </select>

</mapper>

4. Test

postman测试截图:

insert image description here

2. Write the service consumer

由于步骤基本一致,前面一样的步骤就省略啦!

configuration file

Compared with the user service, only the port number is modified

server:
  port: 8061

configuration class

RestTemplate is a network request framework for accessing third-party RESTful API interfaces. This article is used to request user microservices. The configuration is as follows:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    
    
    @Bean
    public RestTemplate restTemplate(){
    
    
        return new RestTemplate();
    }
}

interface layer

import com.example.movie.dto.UserDto;
import com.example.movie.util.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/movieApi")
public class MovieApi {
    
    

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getUserMsgById")
    public ResponseMsg<UserDto> getUserMsg(@RequestParam("id") Integer id){
    
    
        UserDto user = new UserDto();
        ResponseMsg<UserDto> userResponse = restTemplate.getForObject("http://localhost:8060/api/userApi/getUserMsgById/"+id,ResponseMsg.class);
        if(userResponse != null){
    
    
            Map<String,Object> map = (Map<String, Object>) userResponse.getEntity();
            for(String key : map.keySet()){
    
    
                if(key.equals("name")){
    
    
                    user.setName((String) map.get(key));
                }else if(key.equals("user_name")){
    
    
                    user.setUser_name((String) map.get(key));
                }else if(key.equals("age")){
    
    
                    user.setAge((Integer) map.get(key));
                }else if(key.equals("balance")){
    
    
                    user.setBalance((Double) map.get(key));
                }
            }
        }
        return ResponseMsg.success(user);

    }
}

access test

insert image description here

Summarize

提示:这里对文章进行总结:

The above is what I learned today. The final test results shown in the figure above show that the movie microservice can call the API of the user microservice normally.

Guess you like

Origin blog.csdn.net/Shiny_boy_/article/details/125868754