开发环境: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.restclient;

import com.example.restclient.domain.User;
import org.springframework.web.client.RestTemplate; public class RestTemplateMain {
public static void main(String[] args){
RestTemplate tpl = new RestTemplate();
User u = tpl.getForObject("http://localhost:8080/user/lc", User.class);
System.out.println(u.getName() + "," + u.getAge());
}
}

右键Run 'RestTemplateMain.main()',控制台输出:lc,30

3、在bean里面使用RestTemplate,可使用RestTemplateBuilder,新建类 UserService.java

package com.example.restclient.service;

import com.example.restclient.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate; @Service
public class UserService {
@Autowired
private RestTemplateBuilder builder; @Bean
public RestTemplate restTemplate(){
return builder.rootUri("http://localhost:8080").build();
} public User userBuilder(String name){
User u = restTemplate().getForObject("/user/" + name, User.class);
return u;
} }

4、编写一个单元测试类,来测试上面的UserService的bean。

package com.example.restclient.service;

import com.example.restclient.domain.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class UserServiceTest {
@Autowired
private UserService userService; @Test
public void testUser(){
User u = userService.userBuilder("lc");
Assert.assertEquals("lc", u.getName());
}
}

5、控制器类UserController.cs 中调用

配置在application.properties 配置端口和8080不一样,如 server.port = 9001

    @Autowired
private UserService userService; @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user(@PathVariable String name) {
User u = userService.userBuilder(name);
return u;
}

三、使用Feign调用服务

继续在rest-client项目基础上修改代码。

1、pom.xml添加依赖

        <dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.5.0</version>
</dependency> <dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>9.5.0</version>
</dependency>

2、新建接口 UserClient.java

package com.example.restclient.service;

import com.example.restclient.domain.User;
import feign.Param;
import feign.RequestLine; public interface UserClient { @RequestLine("GET /user/{name}")
User getUser(@Param("name")String name); }

3、在控制器类 UserController.java 中调用

decoder(new GsonDecoder()) 表示添加了解码器的配置,GsonDecoder会将返回的JSON字符串转换为接口方法返回的对象。
相反的,encoder(new GsonEncoder())则是编码器,将对象转换为JSON字符串。

    @RequestMapping(value="/user2/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user2(@PathVariable String name) {
UserClient service = Feign.builder().decoder(new GsonDecoder())
.target(UserClient.class, "http://localhost:8080/");
User u = service.getUser(name);
return u;
}

4、优化第3步代码,并把请求地址放到配置文件中。

(1)application.properties 添加配置

application.client.url = http://localhost:8080

(2)新建配置类ClientConfig.java

package com.example.restclient.config;

import com.example.restclient.service.UserClient;
import feign.Feign;
import feign.gson.GsonDecoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class ClientConfig {
@Value("${application.client.url}")
private String clientUrl; @Bean
UserClient userClient(){
UserClient client = Feign.builder()
.decoder(new GsonDecoder())
.target(UserClient.class, clientUrl);
return client;
}
}

(3)控制器 UserController.java  中调用

    @Autowired
private UserClient userClient; @RequestMapping(value="/user3/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user3(@PathVariable String name) {
User u = userClient.getUser(name);
return u;
}

UserController.java最终内容:

package com.example.restclient.web;

import com.example.restclient.domain.User;
import com.example.restclient.service.UserClient;
import com.example.restclient.service.UserService;
import feign.Feign;
import feign.gson.GsonDecoder;
import org.springframework.beans.factory.annotation.Autowired;
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 {
@Autowired
private UserService userService;
@Autowired
private UserClient userClient; @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user(@PathVariable String name) {
User u = userService.userBuilder(name);
return u;
} @RequestMapping(value="/user2/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user2(@PathVariable String name) {
UserClient service = Feign.builder().decoder(new GsonDecoder())
.target(UserClient.class, "http://localhost:8080/");
User u = service.getUser(name);
return u;
} @RequestMapping(value="/user3/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user3(@PathVariable String name) {
User u = userClient.getUser(name);
return u;
}
}

项目结构

先后访问下面地址,可见到输出正常结果

http://localhost:9001/user/lc
http://localhost:9001/user2/lc2
http://localhost:9001/user3/lc3

Spring Boot 2 发布与调用REST服务的更多相关文章

  1. spring boot 集成 Apache CXF 调用 .NET 服务端 WebService

    1. pom.xml加入 cxf 的依赖 <dependency> <groupId>org.apache.cxf</groupId> <artifactId ...

  2. Spring Boot工程发布到Docker

    先聊聊闲话 搞过企业级的application运维的同仁肯定深有感触,每个application的功能交叉错杂,数据交换就让人焦头烂额(当然这和顶层业务设计有关系), 几十个application发布 ...

  3. 使用Ratpack和Spring Boot打造高性能的JVM微服务应用

    使用Ratpack和Spring Boot打造高性能的JVM微服务应用 这是我为InfoQ翻译的文章,原文地址:Build High Performance JVM Microservices wit ...

  4. spring boot项目发布tomcat容器(包含发布到tomcat6的方法)

    spring boot因为内嵌tomcat容器,所以可以通过打包为jar包的方法将项目发布,但是如何将spring boot项目打包成可发布到tomcat中的war包项目呢? 1. 既然需要打包成wa ...

  5. Spring Boot同时开启HTTP和HTTPS服务

    由于Spring Boot中通过编码开启HTTPS服务比较复杂,所以官方推荐通过编码开启HTTP服务,而通过配置开启HTTPS服务. Spring Boot的application.yml中添加如下配 ...

  6. Spring Boot 2.X(十三):邮件服务

    前言 邮件服务在开发中非常常见,比如用邮件注册账号.邮件作为找回密码的途径.用于订阅内容定期邮件推送等等,下面就简单的介绍下邮件实现方式. 准备 一个用于发送的邮箱,本文是用腾讯的域名邮箱,可以自己搞 ...

  7. 翻译-使用Ratpack和Spring Boot打造高性能的JVM微服务应用

    这是我为InfoQ翻译的文章,原文地址:Build High Performance JVM Microservices with Ratpack & Spring Boot,InfoQ上的中 ...

  8. spring boot(二十)使用spring-boot-admin对服务进行监控

    上一篇文章<springboot(十九):使用Spring Boot Actuator监控应用>介绍了Spring Boot Actuator的使用,Spring Boot Actuato ...

  9. WebService—CXF整合Spring实现接口发布和调用过程

    一.CXF整合Spring实现接口发布 发布过程如下: 1.引入jar包(基于maven管理) <!-- cxf --> <dependency> <groupId> ...

随机推荐

  1. spring boot 2 + shiro 实现简单的身份验证例子

    Shiro是一个功能强大且易于使用的Java安全框架,官网:https://shiro.apache.org/. 主要功能有身份验证.授权.加密和会话管理.其它特性有Web支持.缓存.测试支持.允许一 ...

  2. vscode 设置免密远程

    第一步: 生成秘钥 ssh-keygen -t rsa 生成 id_rsa id_rsa.pub cat id_rsa.pub >>  authorized_keys 将私钥文件id_rs ...

  3. Java连载59-局部内部类、匿名内部类

    一.局部内部类 1.局部内部类等同于局部变量 2.局部内部类在访问局部变量的时候,局部变量必须使用final修饰. 3.举个例子: package com.bjpowernode.java_learn ...

  4. Java程序员月薪三万,需要技术达到什么水平?

    最近跟朋友在一起聚会的时候,提了一个问题,说 Java 程序员如何能月薪达到二万,技术水平需要达到什么程度?人回答说这只能是大企业或者互联网企业工程师才能拿到.也许是的,小公司或者非互联网企业拿二万的 ...

  5. 初识微信小程序

    一.简介 微信小程序是运行在微信环境中的应用,它只能在微信中运行,不能运行在浏览器等其他环境中,微信团队提供了专门的开发工具用于微信小程序的开发,还提供了丰富的API,让我们的小程序能够具备与手机设备 ...

  6. (嵌入式)工程模板的创建和MDK下配置开发STM32F103ZE

    ⭐ 我的网站: www.mengyingjie.com ⭐ 遇到此类问题,但看了文章还是未解决, 评论或加 QQ:781378815

  7. PHP $_SERVER超全局变量详解

    参考资料:https://www.php.net/manual/zh/reserved.variables.server.php $_SERVER 是一个包含了诸如头信息(header).路径(pat ...

  8. 使用 Anydesk 5.1 TCP 通道(端口映射)功能从外网方便访问内网的 web/数据库等资源

    Anydesk 5.1 带来一个新的功能:TCP 通道,在家办公时,通过互联网进行远程桌面连接到公司电脑,可以将家用电脑的某个端口,映射到公司网络的某个电脑( IP + 端口),不局限于被远程桌面连接 ...

  9. npm 使用过程中报错问题-及npm使用

    原文地址:https://blog.csdn.net/u013022210/article/details/77740519 1.以下为报错具体详情:node 8.1.2 版本问题:其他空间安装成功但 ...

  10. 快速搭建用于测试的rtsp协议网络流媒体数据服务

    背景: 最近根据项目需求,在平台系统中加入了视频监控显示功能,但是限于没有提供真实可用的监控摄像头数据,通过EasyScreenLive快速搭建了一个rtsp的流媒体服务,下面将实现步骤分享给大家,为 ...