-
前言
利用http://start.spring.io网站生成springboot项目,Dependencies输入web,当前演示的项目名称叫做microservice-simple-cusumer-user,就是一个简单的电影微服务,调用用户微服务[movie api消费了user api]。
-
provider开发步骤——v1【硬编码】
- 1 pom.xml 未改动(略)
- 2 MovieController.java
@RestController
public class MovieController {
// 利用RestTemplate进行调用
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://localhost:7900/simple/" + id, User.class);
}
}
- 3 User.java
import java.math.BigDecimal;
//因为通过RestTemplate调用不需要jpa的注解内容
public class User {
private Long id;
private String username;
private String name;
private Short age;
private BigDecimal balance;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return this.age;
}
public void setAge(Short age) {
this.age = age;
}
public BigDecimal getBalance() {
return this.balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
- 4 application.yml
server:
port: 7901
- 5 接口访问
-
provider开发步骤——v2
- 1 添加注解@Value
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServicePath}")
private String userServicePath;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject(this.userServicePath + id, User.class);
}
}
- 2 application.yml 添加userServicePath配置信息
server:
port: 7901
user:
userServicePath: http://localhost:7900/simple/
-
遇到的问题
v1遇见的问题:Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
答:因为没有new,在启动类上加上添加配置@Bean,此注解的作用是return实例化出来的RestTemplate以方法名restTemplate去命名,即实例化一个RestTemplate对象名叫做restTemplate。
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
上面的这么多代码相当于
private RestTemplate restTemplate = new RestTemplate();