使用Spring Cloud实战微服务(二)电影售票系统——服务消费者

使用Spring Cloud实战微服务(二)电影售票系统——服务消费者

这篇文章与上一篇文章共存亡,因此,要想运行这个案例,首先需要完成上一个案例:https://blog.csdn.net/qq_39422634/article/details/101173273

这篇文章使用RestTemplate调用用户微服务的API,从而查询指定ID的用户信息,在过程开始之前,先看下案例运行效果。输入URL:
http://127.0.0.1:8010/user/1,页面将显示id为1的用户信息记录。
使用Spring Cloud实战微服务(二)电影售票系统——服务消费者_第1张图片

一,使用Spring Initializr快速创建Spring Boot项目

同上篇文章第一步,此处不在赘述:https://blog.csdn.net/qq_39422634/article/details/101173273

二、完善项目内容

1.完善maven配置文件pom.xml



    4.0.0
    com.itmuch.cloud
    microservice-simple-consumer-movie
    0.0.1-SNAPSHOT
    jar

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.9.RELEASE
    

    
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.h2database
            h2
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
    

    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Edgware.RELEASE
                pom
                import
            
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


2.创建用户实体类User.java,该类是一个POJO。

public class User {

    private Long id;
    private String username;
    private String name;
    private Integer age;
    private BigDecimal balance;
    ...get/setXxx()
}

3.创建Controller—MovieController.java,在其中使用RestTemplate请求用户微服务的API。

   @RestController
public class MovieController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id){
        return this.restTemplate.getForObject("http://localhost:8000/" + id, User.class);
    }
}

4.创建启动类ConsumerMovieApplication.java。

@SpringBootApplication
public class ConsumerMovieApplication {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

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

}

5.编写配置文件application.yml。

server:
  port: 8010

6.重头戏来了,先运行前一个项目microservice-simple-provider-user,再运行microservice-simple-consumer-movie,在浏览器中输入URL:http://127.0.0.1:8010/user/1,即可访问到数据,赶快试一下吧!

你可能感兴趣的:(技术小白)