千家信息网

SpringCloud基于RestTemplate微服务项目案例分析

发表于:2024-09-25 作者:千家信息网编辑
千家信息网最后更新 2024年09月25日,本篇内容主要讲解"SpringCloud基于RestTemplate微服务项目案例分析",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"SpringCloud
千家信息网最后更新 2024年09月25日SpringCloud基于RestTemplate微服务项目案例分析

本篇内容主要讲解"SpringCloud基于RestTemplate微服务项目案例分析",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"SpringCloud基于RestTemplate微服务项目案例分析"吧!

基于RestTemplate微服务项目

在写SpringCloud搭建微服务之前,我想先搭建一个不通过springcloud只通过SpringBoot和Mybatis进行模块之间额通讯。然后在此基础上再添加SpringCloud框架。

下面先对案例做个说明

该项目有一个maven父模块,其中里面有三个子模块:

serverspringcloud:整体父工程。

serverspringcloud-api:公共子模块,放公共实体对象。

serverspringcloud-provider-dept-8001:部门微服务提供者。

serverspringcloud-consumer-dept-80:部门微服务消费者。调用部分微服务提供者接口进行CRUD操作。

一、构建父工程

主要步骤:

(1) 创建一个Maven父工程并命名serverspringcloud

(2) 打包方式为POM

(3) 在pom.xml中定义各依赖的版本号(若Module中pom.xml的依赖没有指定版本号,则会根据父工程的版本号加入依赖)

1、创建一个Maven父工程

2、打包方式为POM

3、在pom.xml中定义各依赖的版本号

  4.0.0  com.jincou.springcloudrest  serverspringcloud  0.0.1-SNAPSHOT  pom              UTF-8        1.8        1.8        4.12        1.2.17        1.16.18                                            org.springframework.boot                spring-boot-dependencies                1.5.9.RELEASE                pom                import                                        mysql                mysql-connector-java                5.0.4                                        com.alibaba                druid                1.0.31                                        org.mybatis.spring.boot                mybatis-spring-boot-starter                1.3.0                                        ch.qos.logback                logback-core                1.2.3                                        junit                junit                ${junit.version}                test                                        log4j                log4j                ${log4j.version}                                    serverspringcloud                                    src/main/resources                true                                                        org.apache.maven.plugins                maven-resources-plugin                                                            $                                                                        serverspringcloud-api        serverspringcloud-provider-dept-8001        serverspringcloud-consumer-dept-80    pom.xml

二、构建serverspringcloud-api(公共子模块)

主要步骤

(1) 在父工程下新建Maven的Module,打包方式为jar

(2)在该Module下pom.xml中加入其它需要的依赖

(3) 完成后先clean一下Maven项目,然后再install提供给其它模块调用

1、在父工程下新建Maven的Module,打包方式为jar

在创建完子模块后看下pom.xml的Overview视图的一些信息。

2、 在该Module下pom.xml中加入其它需要的依赖

  4.0.0      com.jincou.springcloudrest    serverspringcloud    0.0.1-SNAPSHOT      serverspringcloud-api   

pom.xml3、我在这里面添加了一个Dept实体

Dept实体

package com.jincou.springcloud.entities;import java.io.Serializable;public class Dept implements Serializable{    private Long     deptno; // 主键    private String     dname; // 部门名称    private String     db_source;// 来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库        public Dept(String dname)    {        super();        this.dname = dname;    }    public Dept(Long deptno, String dname, String db_source) {        super();        this.deptno = deptno;        this.dname = dname;        this.db_source = db_source;    }    public Dept() {        super();    }    public Long getDeptno() {        return deptno;    }    public void setDeptno(Long deptno) {        this.deptno = deptno;    }    public String getDname() {        return dname;    }    public void setDname(String dname) {        this.dname = dname;    }    public String getDb_source() {        return db_source;    }    public void setDb_source(String db_source) {        this.db_source = db_source;    }}

三、创建部门微服务提供者

步骤:这个就比较复杂了,具体看下面的图

下面就展示几个比较重要的环节

1、pom.xml文件

(1)先看下pom.xml的Overview视图的一些信息。

(2)pom.xml

  4.0.0      com.jincou.springcloudrest    serverspringcloud    0.0.1-SNAPSHOT    serverspringcloud-provider-dept-8001                           com.jincou.springcloudrest            serverspringcloud-api            ${project.version}                            junit            junit                            mysql            mysql-connector-java                            com.alibaba            druid                            ch.qos.logback            logback-core                            org.mybatis.spring.boot            mybatis-spring-boot-starter                            org.springframework.boot            spring-boot-starter-jetty                            org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-starter-test                                    org.springframework            springloaded                            org.springframework.boot            spring-boot-devtools            

2、application.yml

server:  port: 8001            #端口号  mybatis:  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径  type-aliases-package: com.jincou.springcloud.entities     # 所有Entity别名类所在包  mapper-locations:  - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件    spring:   application:    name: serverspringcloud-dept             #这个名字很重要后期如果注入eureka就很重要   datasource:    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包    url: jdbc:mysql://localhost:3306/cloudDB01            # 数据库名称    username: root    password: root    dbcp2:      min-idle: 5                                           # 数据库连接池的最小维持连接数      initial-size: 5                                       # 初始化连接数      max-total: 5                                          # 最大连接数      max-wait-millis: 200                                  # 等待连接获取的最大超时时间

3、MySQL表信息

4、DAO接口信息

@Mapperpublic interface DeptDao{    public boolean addDept(Dept dept);//添加部门    public Dept findById(Long id);   //通过id找该部门数据    public List findAll();     //查看所有部门}

5、Controller层类

@RestControllerpublic class DeptController{    @Autowired    private DeptService service;   //添加部门接口    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)    public boolean add(@RequestBody Dept dept)    {        return service.add(dept);    }    //通过部门id查找部门信息    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)    public Dept get(@PathVariable("id") Long id)    {        return service.get(id);    }    //查找所有部门信息    @RequestMapping(value = "/dept/list", method = RequestMethod.GET)    public List list()    {        return service.list();    }}

6、测试

先做个小测试,看数据库连接是否成功,调用api模块是否成功。

说明测试成功!

四、创建部门微服务消费者

主要步骤如图

1、pom.xml文件

  4.0.0      com.jincou.springcloudrest    serverspringcloud    0.0.1-SNAPSHOT    serverspringcloud-consumer-dept-80  部门微服务消费者                          com.jincou.springcloudrest                      serverspringcloud-api            ${project.version}                            org.springframework.boot            spring-boot-starter-web                                    org.springframework            springloaded                            org.springframework.boot            spring-boot-devtools            

2、application.yml

server:  port: 80

3、ConfigBean配置类

@Configurationpublic class ConfigBean //    @Configuration配置   ConfigBean = applicationContext.xml{     @Bean    public RestTemplate getRestTemplate()    {        return new RestTemplate();    } }

4、DeptController_Consumer类

@RestControllerpublic class DeptController_Consumer{    private static final String REST_URL_PREFIX = "http://localhost:8001";    /**     * 使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap,     * ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。     */    @Autowired    private RestTemplate restTemplate;    @RequestMapping(value = "/consumer/dept/add")    public boolean add(Dept dept)    {        return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);    }    @RequestMapping(value = "/consumer/dept/get/{id}")    public Dept get(@PathVariable("id") Long id)    {        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);    }    @SuppressWarnings("unchecked")    @RequestMapping(value = "/consumer/dept/list")    public List list()    {        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);    }}

5、测试

测试成功,当我调用消费者接口的时候,它会再去调用提供者的接口。

到此,相信大家对"SpringCloud基于RestTemplate微服务项目案例分析"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0