(030)Spring Boot之RestTemplate访问web服务案例

  每一个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>

  Product.java

package com.edu.spring.mall.product.bean;

import java.sql.Timestamp;

public class Product {

    private Integer pid;
    private String pname;
    private String type;
    private double price;
    private Timestamp createTime;

    public Integer getPid() {
        return pid;
    }
    public void setPid(Integer pid) {
        this.pid = pid;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Timestamp getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [pid=" + pid + ", pname=" + pname + ", type=" + type
                + ", price=" + price + ", createTime=" + createTime + "]";
    }

}

  ProductMapper.java

package com.edu.spring.mall.product.bean;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface ProductMapper {

    @Insert("insert into t_products (pname,type,price) values (#{pname},#{type},#{price})")
    Integer add(Product product);

    @Delete("delete from t_products where pid=#{arg1}")
    Integer deleteById(Integer id);

    @Update("update t_products set pname=#{pname},type=#{type},price=#{price} where pid=#{pid}")
    Integer update(Product product);

    @Select("select * from t_products where pid=#{arg1}")
    Product getById(Integer id);

    @Select("select * from t_products order by pid desc ")
    List<Product> queryByLists();
}

  Response.java

package com.edu.spring.mall.product.web;

public class Response {

    private String code;
    private String msg;
    private Object data;

    public Response(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Response(String code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

}

  ProductController.java

package com.edu.spring.mall.product.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.edu.spring.mall.product.bean.Product;
import com.edu.spring.mall.product.bean.ProductMapper;
import com.edu.spring.mall.product.web.Response;

@RestController
public class ProductController {

    @Autowired
    private ProductMapper productMapper;

    @PostMapping("/soa/product/add")
    public Object add(Product product){
        Integer res=productMapper.add(product);
        return res==1?new Response("200","ok"):new Response("500","fail");
    }

    @DeleteMapping("/soa/product/{id}")
    public Object delete(@PathVariable("id") Integer id){
        Integer res=productMapper.deleteById(id);
        return res==1?new Response("200","ok"):new Response("500","fail");
    }

    @PostMapping("/soa/product/update")
    public Object update(Product product){
        Integer res=productMapper.update(product);
        return res==1?new Response("200","ok"):new Response("500","fail");
    }

    @GetMapping("/soa/product/{id}")
    public Object getById(@PathVariable("id") Integer id){
        Product product=productMapper.getById(id);
        return new Response("200","OK", product);
    }

    @GetMapping("/soa/product/list")
    public Object list(){
        return new Response("200","OK",productMapper.queryByLists());
    }
}

  App.java

package com.edu.spring.mall.product;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

  application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3309/db_products
spring.datasource.username=root
spring.datasource.password=123456

  product.sql

create database db_products default charset utf8;
create table t_products(pid int not null primary key auto_increment,pname varchar(200),type varchar(10),price double,createTime timestamp) 

(二)创建一个客户端工程,mall-web

  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.web</groupId>
    <artifactId>mall-web</artifactId>
    <version>1.0.0</version>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>
    </dependencies>

</project>

  Product.java

package com.edu.spring.mall.web.bean;

public class Product {

    private Integer pid;
    private String pname;
    private String type;
    private double price;
    private String createTime;

    public Integer getPid() {
        return pid;
    }
    public void setPid(Integer pid) {
        this.pid = pid;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [pid=" + pid + ", pname=" + pname + ", type=" + type
                + ", price=" + price + ", createTime=" + createTime + "]";
    }

}

  Response.java

package com.edu.spring.mall.web.bean;

public class Response {

    private String code;
    private String msg;
    private Product data;

    public Response(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Response(String code, String msg, Product data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Product data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Response [code=" + code + ", msg=" + msg + ", data=" + data
                + "]";
    }

}

  App.java

package com.edu.spring.web;

import org.springframework.web.client.RestTemplate;

import com.edu.spring.mall.web.bean.Response;
import com.google.gson.Gson;

public class App
{
    public static void main( String[] args )
    {
        String BASE_URL="http://127.0.0.1:8080";
        RestTemplate res=new RestTemplate();
        String body= res.getForObject(BASE_URL+"/soa/product/20",String.class);
        System.out.println(body);
        Gson gson=new Gson();
        Response response=gson.fromJson(body,Response.class);
        System.out.println(response);
        System.out.println(response.getCode());
        System.out.println(response.getMsg());
        System.out.println(response.getData());
    }
}

  (三)首先启动 mall-product,然后启动 mall-web,截图如下:

  

原文地址:https://www.cnblogs.com/javasl/p/11966678.html

时间: 2024-10-07 11:32:03

(030)Spring Boot之RestTemplate访问web服务案例的相关文章

SpringBoot实战(十)之使用Spring Boot Actuator构建RESTful Web服务

一.导入依赖 <?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.

[译]Spring Boot 构建一个RESTful Web服务

翻译地址:https://spring.io/guides/gs/rest-service/ 构建一个RESTful Web服务 本指南将指导您完成使用spring创建一个“hello world”RESTful Web服务的过程. 你将会构建什么 您将构建一个将接受HTTP GET请求的服务: 您将构建一个将接受HTTP GET请求的服务: http://localhost:8080/greeting 1 1 并且使用JSON的形式进行响应: {"id":1,"conten

Spring提供的用于访问Rest服务的客户端:RestTemplate实践

什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率.调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式.ClientHttpRequestFactory接口主要提供了两种实现方式

使用Spring Boot来加速Java web项目的开发

使用Spring Boot来加速Java web项目的开发 我想,现在企业级的Java web项目应该或多或少都会使用到Spring框架的. 回首我们以前使用Spring框架的时候,我们需要首先在(如果你使用Maven的话)pom文件中增加对相关的的依赖(使用gradle来构建的话基本也一样)然后新建Spring相关的xml文件,而且往往那些xml文件还不会少.然后继续使用tomcat或者jetty作为容器来运行这个工程.基本上每次创建一个新的项目都是这么一个流程,而我们有时候仅仅想快速的创建一

如何使用RestTemplate访问restful服务

https://www.jianshu.com/p/c9644755dd5e 一. 什么是RestTemplate 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate. 二.一个简单的例子. 定义一个简单的restful接口 @RestController public class TestController { @RequestMappin

Spring Boot入门-快速搭建web项目

Spring Boot 概述: Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum

Spring MVC或Spring Boot配置默认访问页面不生效?

相信在开发项目过程中,设置默认访问页面应该都用过.但是有时候设置了却不起作用.你知道是什么原因吗?今天就来说说我遇到的问题. 首先说说配置默认访问页面有哪几种方式. 1.tomcat配置默认访问页面 进入 tomcat 的 conf 目录,编辑 web.xml 文件.在 <web-app></web-app> 添加默认访问页面. <welcome-file-list> <welcome-file>index.html</welcome-file>

Spring Boot 之FilterRegistrationBean --支持web Filter 排序的使用(转)

Spring Boot 之FilterRegistrationBean  --支持web Filter 排序的使用Spring 提供了FilterRegistrationBean类,此类提供setOrder方法,可以为filter设置排序值,让spring在注册web filter之前排序后再依次注册. 写一个普通的filter: package com.sdcuike.practice.web2; import java.io.IOException; import javax.annotat

使用Ratpack与Spring Boot构建高性能JVM微服务

在微服务天堂中Ratpack和Spring Boot是天造地设的一对.它们都是以开发者为中心的运行于JVM之上的web框架,侧重于生产率.效率以及轻量级部署.他们在服务程序的开发中带来了各自的好处.Ratpack通过一个高吞吐量.非阻塞式的web层提供了一个反应式编程模型,而且对应用程序结构的定义和HTTP请求过程提供了一个便利的处理程序链:Spring Boot集成了整个Spring生态系统,为应用程序提供了一种简单的方式来配置和启用组件.Ratpack和Spring Boot是构建原生支持计