Рассмотрим способо обращения к Rest-сервису, на примере микросервисов. Так же в скользь будет рассмотрен способ избежения дублирования кода в микросервисах. Я использую данную статью, позже, планирую ее перевести.
Первым делом реализуем библиотечную часть, которая будет использоваться во всех частях микросервиса для обмена.
package com.example.user.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.ArrayList;
import java.util.List;
/**
* Created by bartoszjedrzejewski on 08/06/2016.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserView {
private long id;
private String forename;
private String surname;
private String organisation;
private List notifications;
private long points;
public UserView(){
}
public long getId() {
return id;
}
public String getForename() {
return forename;
}
public String getSurname() {
return surname;
}
public String getOrganisation() {
return organisation;
}
public List getNotifications() {
return notifications;
}
public long getPoints() {
return points;
}
}
и pom-файл для мавена:
4.0.0 com.example user-client-libs 0.0.1-SNAPSHOT com.fasterxml.jackson.core jackson-annotations 2.6.6
Теперь рассмотрим микросервис, предоставляющий информацию о пользователе.
Пользователь:
package com.example;
import java.util.ArrayList;
import java.util.List;
/**
* Created by bartoszjedrzejewski on 08/06/2016.
*/
public class User {
private final long id;
private final String forename;
private final String surname;
private final String organisation;
private final List notifications;
private final long points;
//Friends are deprecated and should not be used
private final List friends;
public User(int id) {
String[] forenames = {"Alice", "Manjula", "Bartosz", "Mack"};
String[] surnames = {"Smith", "Salvatore", "Jedrzejewski", "Scott"};
String[] organisations = {"ScottLogic", "UNICEF"};
forename = forenames[id%3];
surname = surnames[id%4];
organisation = organisations[id%2];
notifications= new ArrayList<>();
notifications.add("You have been promoted!");
notifications.add("Sorry, disregard the previous notifaction- wrong user");
points = id * 31 % 1000;
//You have no friends
friends = new ArrayList<>();
this.id = id;
}
public long getId() {
return id;
}
public String getForename() {
return forename;
}
public String getSurname() {
return surname;
}
public String getOrganisation() {
return organisation;
}
public List getNotifications() {
return notifications;
}
public long getPoints() {
return points;
}
public List getFriends() {
return friends;
}
}
Обычный Rest-контроллер:
package com.example;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by bartoszjedrzejewski on 08/06/2016.
*/
@RestController
public class UserController {
@RequestMapping("/user")
public User getUser(@RequestParam(value="id", defaultValue="1") int id) {
return new User(id);
}
}
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
Для настройки порта используется файл application.properties.Укажем в нем: server.port = 9001
pom-файл:
Простенький Rest-контроллер, который обращается к выше описанному микросервису:4.0.0 com.example user-service 0.0.1-SNAPSHOT jar user-service Demo user-service with Spring Boot org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test com.fasterxml.jackson.core jackson-databind 2.5.0 org.springframework.boot spring-boot-maven-plugin
package com.example;
import com.example.user.dto.UserView;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Created by bartoszjedrzejewski on 09/06/2016.
*/
@RestController
public class UserDashboardController {
@RequestMapping("/dashboard")
public String getUser(@RequestParam(value="id", defaultValue="1") int id) {
RestTemplate restTemplate = new RestTemplate();
UserView user = restTemplate.getForObject("http://localhost:9001/user?id="+id, UserView.class);
return "USER DASHBOARD
" +
"Welcome " + user.getForename() +" "+user.getSurname()+"
"+
"You have " +user.getPoints() + " points! Good job!
"+
"
"+
"
"+user.getOrganisation();
}
}
Запускалочка:package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(UserDashboardApplication.class, args);
}
}
порт: server.port = 9002
pom-файл:
Вот и все, что нужно для обращения к Rest сервису. Все за нас делает объект RestTemplate. Конечно же можно выполнять не только Get запросы, но и post (postForObject(URI url, Object request, Class4.0.0 com.example user-dashboard 0.0.1-SNAPSHOT jar user-dashboard Demo user-dashboard service with Spring Boot org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test com.example user-client-libs 0.0.1-SNAPSHOT org.springframework.boot spring-boot-maven-plugin