springboot- publishing and cross-domain debugging REST services 02--

Disclaimer: This article is a blogger original article, by allowing the bloggers are free to share, try not to be used for commercial purposes. https://blog.csdn.net/matrixbbs/article/details/90640361

Publishing and calling REST services

  • SOAP can be used
  • You can also use REST, REST, for example in this case still

Representational State Transfer === REST

  • It is an architectural style
  • It is a lightweight HTTP-based Web Service style
  • It is a design principle
  • Also a design idea

Examples whole idea of ​​building

  • Build server

  • Build client

    • Test and call REST services, with 8085, the port, in application.properties Complete the appropriate settings can
    • Use RestTemplate class to call the service, this class is provided by the Spring Framework
    • Three test mode
      • 1 run directly using the main way to access REST services
      • 2 Use JUNIT test method to access the REST service
      • 3 Use the controller to access the WEB REST services
    • Project name: spring-rest-client

Common parts - two projects will be used, duplicate definitions

In the present example, the server project, to define it as an internal class can be used directly

  • Circulation object definition: Person.java
package com.fhzheng.demo;
// 流转数据对象
public class Person{
	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;
	}
}

1 server project realization

Here Insert Picture Description
Specific server code

package com.fhzheng.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController 
public class SpringRestServerApplication {

	// 启动器
	public static void main(String[] args) {
		SpringApplication.run(SpringRestServerApplication.class, args);
	}
	
	// 控制器
	@GetMapping(value="/person/{name}",produces = MediaType.APPLICATION_JSON_VALUE)
	public Person person(@PathVariable String name) {
		Person p = new Person();
		p.setName(name);
		p.setAge(33);
		return p;
	}
	
	// 流转数据对象
	static class Person{
		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;
		}
	}

}

2 client project realization

Here Insert Picture Description
Specific code to achieve
before Person.java has provided
MyService.java

package com.fhzheng.demo;

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 MyService {

	@Autowired
	private RestTemplateBuilder builder;
	
	@Bean
	public RestTemplate restTemplate() {
		return builder.rootUri("http://localhost:8080").build();
	}
	
	public Person useBuilder() {
		Person p = restTemplate().getForObject("/person/fhzheng999", Person.class);
		return p;
	}
}

Rest Template Main .java

package com.fhzheng.demo;

import org.springframework.web.client.RestTemplate;

public class RestTemplateMain {

	/**
	 * 	用一个普通方法,直接完成对REST服务的请求
	 * @param args
	 */
	public static void main(String[] args) {

		RestTemplate tpl = new RestTemplate();
		Person p = tpl.getForObject("http://localhost:8080/person/fhzheng777", Person.class);
		System.out.println(p.getName()+"---"+p.getAge());
	}

}

JUNIT test code SpringRestClient1ApplicationTests.java

package com.fhzheng.demo;

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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)	//保证web容器不被启动,只做单元测试
public class SpringRestClient1ApplicationTests {

	@Autowired 
	private MyService myService;
	
	@Test
	public void testUserTemplate() {
		Person p = myService.useBuilder();
		System.out.println(p.getName() + "==="+ p.getAge());
	}
	
	@Test
	public void contextLoads() {
	}

}

application.properties profile content
server here uses the default port publishing services, namely 8080
client calls the service, the client issues port 8085

# server
server.port = 8085

The client starters and controllers

package com.fhzheng.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
public class SpringRestClient1Application {

	public static void main(String[] args) {
		SpringApplication.run(SpringRestClient1Application.class, args);
	}

	// 控制器
	/**
	 * 	用跨域方式,完成对REST服务的请求
	 * 	注意,WEB服务启动起来时,客户端端口号不能和服务器端端口号重叠,保证跨域状态
	 * @return
	 */
	@GetMapping(value="/client")
	public Person clientGetPerson() {
		RestTemplate tpl = new RestTemplate();
		Person p = tpl.getForObject("http://localhost:8080/person/fhzheng777", Person.class);
		System.out.println(p.getName()+"---"+p.getAge());
		return p;
	}
}

operation result

The server runs the test

Here Insert Picture Description

The client runs test

1 main test results

Here Insert Picture Description

2 JUNIT test results

Here Insert Picture Description

3 client WEB test run results

Here Insert Picture Description

postscript

  • RestTemplate just one of many of a REST client. There are many, such as:
    • Feign framework
    • Restlet framework
    • CXF framework
      they can realize calls to REST services, use them, it simply is: simplifies the process of initiating HTTP requests and process responses, and supports REST. Why simplify it

What is RestTemplate

Version 3.0, Spring provides RestTemplate as a client for accessing Rest services, RestTemplate offers a variety of convenient methods to access the remote Http services, can greatly improve the efficiency of the preparation of the client. Our own package HttpClient, usually some template code, such as establishing a connection, the request header and request body structure, then the response, parse the response information, and then close the connection. Spring RestTemplate is again encapsulate the HttpClient, simplifies the process of initiating the HTTP request and response process, a higher level of abstraction, reduce consumer template code, so that less redundant code. In fact, think about it a lot XXXTemplate class at Spring Boot, they also provide a variety of templates method, except higher level of abstraction, hiding it in more detail. Incidentally, Spring Cloud has a declarative service call Feign, it is based Netflix Feign implementation, integration with Spring Cloud Ribbon Spring Cloud Hystrix, and to achieve a declarative way to define Web service client.
Essentially Feign is based RestTemplate again on its packaging, which it has to help us define and implement the definition of dependent services interface.

Guess you like

Origin blog.csdn.net/matrixbbs/article/details/90640361