每一个springboot工程都可以看做一个服务,这也是微服务的基础,使用RestTemplate访问springboot提供的web服务。如下:

String BASE_URL="http://127.0.0.1:8080";
RestTemplate res=new RestTemplate();
String body= res.getForObject(BASE_URL+"/soa/product/20",String.class);//请求服务,返回json字符串
System.out.println(body);
Gson gson=new Gson();
Response response
=gson.fromJson(body,Response.class);//将json字符串转化为实体类 System.out.println(response); System.out.println(response.getCode()); System.out.println(response.getMsg()); System.out.println(response.getData());

  创建过程及源码如下:

(一)首先新建一个springboot工程,mall-product

  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.edu.spring.mall</groupId>
    <artifactId>mall-product</artifactId>
    <version>1.0.0</version>

    <name>mall-product</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.0.4.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </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-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
</project>
View Code

相关文章:

  • 2021-08-14
  • 2021-09-24
  • 2022-12-23
  • 2021-07-06
  • 2022-03-03
  • 2022-12-23
  • 2022-01-07
  • 2021-10-30
猜你喜欢
  • 2022-12-23
  • 2021-08-10
  • 2022-12-23
  • 2021-11-18
  • 2021-11-06
相关资源
相似解决方案