Spring Boot 2 发布与调用REST服务

本文介绍了如何使用Spring Boot 2发布REST服务,并通过RestTemplate和Feign两种方式调用这些服务。首先创建了一个名为rest-server的项目,发布REST服务,然后在rest-client项目中,利用RestTemplate直接调用服务并展示结果。接着,通过Feign进行服务调用的优化,将请求地址配置到application.properties中,最后展示了所有接口的正常运行输出。
摘要由CSDN通过智能技术生成

开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

一、发布REST服务

1、IDEA新建一个名称为rest-server的Spring Boot项目

2、新建一个实体类User.java

package com.example.restserver.domain;

public class User {
    String name;
    Integer age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

3、新建一个控制器类 UserController.java

package com.example.restserver.web;

import com.example.restserver.domain.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user(@PathVariable String name) {
        User u = new User();
        u.setName(name);
        u.setAge(30);
        return u;
    }
}

项目结构如下:

  

 访问 http://localhost:8080/user/lc,页面显示:

{"name":"lc","age":30}

二、使用RestTemplae调用服务

1、IDEA新建一个名称为rest-client的Spring Boot项目

2、新建一个含有main方法的普通类 RestTemplateMain.java,调用服务

package com.example.restc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值