Spring Boot 2 发布与调用REST服务

2019-09-23 09:11:08来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Spring Boot 2 发布与调用REST服务

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

一、发布REST服务

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

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

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.cs

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.cs,调用服务

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.cs

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.cs

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.cs 中调用

    @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.cs

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.cs  中调用

    @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.cs最终内容:

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
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:PlayJava Day025

下一篇:【Java学习】类、对象、实例—类是对象的抽象,对象是类的实例