Spring Boot2发布调用REST服务实现方法
作者:gdjlc 发布时间:2023-12-10 20:03:49
开发环境: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
来源:https://www.cnblogs.com/gdjlc/p/11565311.html


猜你喜欢
- (一)首先说Unity调用页面方法的办法。首先是需要在工程的Asset目录里面建一个Plugins文件夹,然后在文件夹里面创建一个.txt文
- 简介官方API文档Scaffold的of方法说明有说明调用Scaffold.of方法是在Scallfold的子组件的Build方法中,也就是
- 本文主要介绍了Android studio利用gradle打jar包并混淆的方法,下面话不多说,来看看详细的介绍吧。首先打jar包的配置很简
- Sentinel流控模式Sentinel流量控制主要有以下几种模式:直接失败模式:在达到流量控制阈值后,直接拒绝请求,返回错误信息。关联模式
- C# 4.0提供了一个dynamic 关键字,那么什么是dynamic,究竟dynamic是如何工作的呢?从最简单的示例开始:static
- 前言Service是Android系统的四大组件之一。在Android系统中,Service可以用来执行一些需要在后台长期运行的任务,也可以
- VelocityTracker顾名思义即速度跟踪,在android中主要应用于touch even。Velocit
- 前言C#中Try-Catch语句大家都很熟悉了,但是细究起来,还是有很多东西可讲的。最近在翻看之前总结的常见面试题中,发现关于try...c
- 前言:回顾之前的微信公众号配置和消息处理的内容,我们已经掌握了如何配置服务器与微信公众号建立连接,也掌握了通过消息管理的方式,对用户的信息进
- 简介java中可以被称为Number的有byte,short,int,long,float,double和char,我们在使用这些Nubme
- 在《阿里巴巴java开发手册》中指出了线程资源必须通过线程池提供,不允许在应用中自行显示的创建线程,这样一方面是线程的创建更加规范,可以合理
- 使用范围: 只能作用在方法和构造函数之上@SneakyThrows注解的作用得从java的异常设计体系说起。java中常见的异常有两种:Ex
- Android 中倒计时验证两种常用方式实例详解短信验证码功能,这里总结了两种常用的方式,可以直接拿来使用。看图:说明:这里的及时从10开始
- 登录接口实现public User queryUser(String UserName, String Password,HttpServl
- 前言 图片加水印:Springboot 图片需要添加水印,怎么办? 1秒就实现那么word文档替换文字、插入图片,当然也是1秒钟了
- 代理对象的生成方法是:Proxy.newProxyInstance(...) ,进入这个方法内部,一步一步往下走会发现会调用ProxyGen
- Hadoop环境搭建详见此文章https://www.jb51.net/article/33649.htm。我们已经知道Hadoop能够通过
- Maven中建立的依赖管理方式基本已成为Java语言依赖管理的事实标准,Maven的替代者Gradle也基本沿用了Maven的依赖管理机制。
- 建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。这是建造者模式的标准表达,不过看着让人迷惑,什么叫构建
- 归并排序原理1.尽可能的一组数据拆分成两个元素相等的子组,并对每一个子组继续拆分,直到拆分后的每个子组的元素个数是1为止。⒉将相邻的两个子组