(1)hell word 之spring cloud

1.1 介绍


       主要是方便跟我一样的新手入门。
1.先创建提供者项目:microservice-provider-user







引用

(1)打开http://start.spring.io/ 地址
(2)版本选中1.5.3, group我的填写为 com.hongchen.cloud
(3)artifact填写 microservice-provider-user
(4)dependencies 里面需选中 Web,Jpa, H2
(5)点击generate projecy生成项目,它会自动下载
如:下图:




到此我们的提供者已经创建完毕,接下来创建我们的消费者microservice-consumer-movie.

同样的步骤:



引用

(1)打开http://start.spring.io/ 地址
(2)版本选中1.5.3, group我的填写为 com.hongchen.cloud
(3)artifact填写 microservice-consumer-movie
(4)dependencies 里面需选中 Web 只需要web即可
(5)点击generate projecy生成项目,它会自动下载



如:下图:


好了我们的两个项目已经创建完毕,接下来就从我们的下载文件找到这两个项目,进行解压,一个好的程序员肯定会有一个良好的习惯,建议把刚下载的两个zip包放在一个目录进行管理:如下图:


2.导入我们刚刚解压好的项目,此时需要等待一段时间。

4.在提供者项目microservice-provider-user编写hello word提供接口



[code="java"]package com.hongchen.cloud.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by lichongda on 2017/5/2.
*/
@RestController
public class HelloWordController {
   @GetMapping("hello")
    public String findById(){
        return "hello word";
    }
}

  4.配置文件application.yml

[code="java"]server:
  port: 7900

项目结构如下图:

5.启动我们的项目:查看我们的控制台,如果你们是按照我的方法来,控制台应该不会出错.

6.编写我们的消费者项目microservice-consumer-movie

    HelloWordController.class类

[code="java"]package com.hongchen.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
* Created by lichongda on 2017/5/2.
*/
@RestController
public class HelloWordController {
    @Autowired
    private RestTemplate restTemplate;
   @GetMapping("hello")
    public String findById(){
       return  this.restTemplate.getForObject("http://localhost:7900/hello/+", String.class);
    }
}
   

     配置文件application.yml

[code="java"]server:
  port: 7901
  

    启动类得有变动如下:

  

[code="java"]package com.hongchen.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class MicroserviceConsumerMovieApplication {
@Bean
public RestTemplate restTemplate(){
return  new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerMovieApplication.class, args);
}
}

项目结构如下图:
 
   如果RestTemplate不初始化是无法在控制层使用,切记切记

此时启动我们的项目:就可以调用提供者了。在页面上输入:http://localhost:7900/hello

结果如下图:
 

到此我们的hello word已结束。
欢迎进群一起讨论: 183153579

猜你喜欢

转载自lichongda.iteye.com/blog/2372231
今日推荐