SpringCloud小白级入门——消费者

  • 前言

利用http://start.spring.io网站生成springboot项目,Dependencies输入web,当前演示的项目名称叫做microservice-simple-cusumer-user,就是一个简单的电影微服务,调用用户微服务[movie api消费了user api]

  • provider开发步骤——v1【硬编码】

  1. 1 pom.xml 未改动(略)

 

  1.  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);
    }
}
  1. 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;
    }

}
  1. 4 application.yml
server:
  port: 7901
  1. 5 接口访问

  

  • provider开发步骤——v2

  1.  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);
  }
}

  1. 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();

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值