SpringCloud之服务提供者和服务消费者

编写服务提供者
编写服务消费者
微服务构建的是分布式系统,各个微服务之间通过网络进行通信。一般我们用服务提供者和服务消费者来描述微服务之间的调用关系:

服务提供者 - 服务被调用方

服务消费者 - 服务的调用方

以售票系统为例,用户向12306售票系统发起购票请求,在进行购买业务之前,12306售票系统需要先调用用户微服务接口,查看用户的相关信息是否符合购买标准等相关信息,这里,用户微服务就是服务的提供者,售票系统微服务就是服务消费者。下面依次在Intellij idea中手动创建这两个微服务:

先创建用户微服务:maven的pom.xml文件信息如下:

<?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>com.simons.cn</groupId>
    <artifactId>user-provider</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
    </properties>
    <dependencies>
        <!--支持web应该用开发,包括spring-mvc、jackson、tomcat、spring-webmvc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--springboot Actuator提供了众多检测端点,了解应用程序的运行状况-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--配置mybatis启动器依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.22</version>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.12</version>
            <scope>provided</scope>
        </dependency>
 
    </dependencies>
    <!-- 引入spring cloud的依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!-- 添加spring-boot的maven插件 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

生成项目后,把通过mybatis反向生成的实体和xml文件copy到相关目录(mybatis反向生成点这里),目录如图:

这里要注意要修改UserMapper.xml中Mapper和User类为你实际路径。

接着编写启动类ProviderUserApplication:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
//扫描*Mapper.java接口文件
@MapperScan("com.simons.cn.mapper")
@SpringBootApplication
public class PrividerUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(PrividerUserApplication.class);
    }
}

@SpringBootApplication是一个组合注解,它整合了@Configuration、@EnableAutoConfiguration和@ComponentScan注解,并且开启了springboot程序组件扫描和自动配置功能;@MapperScan注解用来扫描mapper接口。

接着编写UserController类:

import com.simons.cn.bean.User;
import com.simons.cn.service.UserServiceImpl;
import com.simons.cn.util.CommonEnum;
import com.simons.cn.util.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
 
@Slf4j
@RestController
public class UserController {
 
    @Autowired
    private UserServiceImpl userService;
 
    @GetMapping(value = "/getuserinfo")
    public CommonResult getUserInfo(@RequestParam(required = false,value = "name") String name){
        List<User> userList = userService.getUserByName(name);
        return CommonResult.success(CommonEnum.SUCESS.getCode(),CommonEnum.SUCESS.getMessage(),userList);
    }
}

@RestController注解声明等价于@Controller和@ResponseBody注解联合作用,标识该类均返回一个rest风格的data;@GetMapping是spring4.3提供的新注解,等价于@RequestMapping(value="/{id}",method=RequestMethod.GET),同理还有@PostMapping()等。

接着编写配置文件application.yml或application.properties均可,我这里是application.yml

server:
  port: 8000
# 数据库连接信息
spring:
  datasource:
           url: jdbc:mysql://×××:3306/simons?rewriteBatchedStatements=true&characterEncoding=utf-8
           username: ×××
           password: ×××
           driver-class-name: com.mysql.jdbc.Driver
# mybatis扫描信息
mybatis:
  typeAliasesPackage: com.simonsfan.study.bean  #实体对象所以在包
  mapper-locations: classpath:mapper/*.xml       #xml文件位置

需要注意的是,yml文件中冒号后面要空一格,例如port: 8000冒号后面一定要空格再接8000

接下来可以启动ProviderUserApplication启动类。

测试:浏览器访问http://localhost:8000/getuserinfo?name=jack,返回

{
  "code": "0",
  "message": "success",
  "data": [{
    "id": 125,
    "name": "jack",
    "role": "system"}]
}

这样,用户微服务就顺利完成。同理,可以编写售票系统的服务消费者。pom.xml文件基本不变

<?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>com.simons.cn</groupId>
    <artifactId>ticket-coucumer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
    </properties>
    <dependencies>
        <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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.22</version>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <!-- 引入spring cloud的依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!-- 添加spring-boot的maven插件 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

接着我把刚才服务提供者里面要用的一些类都copy到服务消费者来,目录结构如下:

编写启动类ConsumerApplication:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
 
@SpringBootApplication
public class ConsumerApplication {
 
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
 
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

其中@Bean是一个方法注解,作用是实例化一个Bean并使用该方法的名称命名,本例中的用法等价于RestTemplate restTemplate = new RestTemplate()

接着创建TicketController:

import com.simons.cn.util.CommonResult;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
@Slf4j
@RestController
public class TicketController {
 
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/ticketpurchase")
    public CommonResult purchaseTicket(@RequestParam(required = false,value = "name") String name){
        //模拟判断用户身份
        CommonResult result = restTemplate.getForObject("http://localhost:8000/getuserinfo?name=" + name, CommonResult.class);
        //买票下单逻辑略
        return result;
    }
 
}

这里要注意的是,刚才编写的CommonResult类中一定要添加无参构造函数,否则上面的调用会报错!!!

编写application.yml文件:

server:
  port: 8888

这样,售票微服务也完成了。启动ConsumerApplication启动类

测试:浏览器访问:http://localhost:9000/ticketpurchase?name=jack,结果如下:

{
  "code": "0",
  "message": "success",
  "data": [{
    "id": 125,
    "name": "jack",
    "role": "system"
    }]
}

说明售票微服务已经可以正常使用RestTemplate和用户微服务API通信了。

项目的github:https://github.com/simonsfan/SpringCloud.git

转载自 : https://blog.csdn.net/fanrenxiang/article/details/78274682  

侵权必删!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【2021年,将Spring全家桶系列课程进行Review,修复顺序等错误。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并新增高级的Spring Security等内容,通过手把手一步步教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待】 本课程是Spring案例精讲课程的第四部分Spring Cloud,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Cloud的核心知识点:注册中心、服务提供者与消费者服务的调用OpenFeign、Hystrix监控、服务网关gateway、消息驱动的微服务Spring Cloud Stream、分布式集群、分布式配置中心的案例介绍, 快速掌握Spring Cloud的核心知识,快速上手,为学习及工作做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值