Spring Boot2发布调用REST服务实现方法

 更新时间:2020年04月23日 16:03:58   作者:gdjlc  
这篇文章主要介绍了Spring Boot2发布调用REST服务实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java中的CAS锁机制(无锁、自旋锁、乐观锁、轻量级锁)详解

    Java中的CAS锁机制(无锁、自旋锁、乐观锁、轻量级锁)详解

    这篇文章主要介绍了Java中的CAS锁机制(无锁、自旋锁、乐观锁、轻量级锁)详解,CAS算法的作用是解决多线程条件下使用锁造成性能损耗问题的算法,保证了原子性,这个原子操作是由CPU来完成的,需要的朋友可以参考下
    2024-01-01
  • Flink部署集群整体架构源码分析

    Flink部署集群整体架构源码分析

    这篇文章主要为大家介绍了Flink部署集群及整体架构示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • Java内存模型(JMM)及happens-before原理

    Java内存模型(JMM)及happens-before原理

    这篇文章主要介绍了java内存模型(JMM)及happens-before原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Java中的模板模式说明与实现

    Java中的模板模式说明与实现

    这篇文章主要介绍了Java中的模板模式说明与实现,模板方法模式,又叫模板模式,在一个抽象类公开定义了执行它的方法的模板,它的子类可以更需要重写方法实现,但可以成为典型类中定义的方式进行,需要的朋友可以参考下
    2023-10-10
  • 手动实现将本地jar添加到Maven仓库

    手动实现将本地jar添加到Maven仓库

    这篇文章主要介绍了手动实现将本地jar添加到Maven仓库方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • Java动态加载类示例详解

    Java动态加载类示例详解

    这篇文章主要给大家介绍了关于Java动态加载类的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • 新手了解java基础知识(二)

    新手了解java基础知识(二)

    这篇文章主要介绍了Java基础知识,本文介绍了Java语言相关的基础知识、历史介绍、主要应用方向等内容,需要的朋友可以参考下,希望对你有所帮助
    2021-07-07
  • 你知道Java中的注解可以继承吗?

    你知道Java中的注解可以继承吗?

    注解想必大家都用过,也叫元数据,是一种代码级别的注释,可以对类或者方法等元素做标记说明。那么今天我想问大家的是类被继承了,注解能否继承呢?可能会和大家想的不一样,感兴趣的可以往下看
    2022-12-12
  • 基于Java在netty中实现线程和CPU绑定

    基于Java在netty中实现线程和CPU绑定

    这篇文章主要介绍了基于Java在netty中实现线程和CPU绑定,文章围绕主题的相关内容展开详细介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • Java中的CountDownLatch源码解析

    Java中的CountDownLatch源码解析

    这篇文章主要介绍了Java中的CountDownLatch源码解析,CountDownLatch类是一个同步辅助装置,允许一个或多个线程去等待直到另外的线程完成了一组操作,需要的朋友可以参考下
    2023-12-12

最新评论