Spring Cloud搭建微服務架構----使用Spring boot開發web項目

項目服務實例之間主要經過RestAPI方式進行通訊,因此服務自己可藉助SpringBoot快速開發Restful web API。java

開發Restful web服務

以 http get方式訪問:http://localhost:8080/hellogit

獲取響應:{"id":1,"content":"Hello, World!"}github

使用工具:web

  • IDEA;
  • Mven3;

實體類

Hello.javaspring

package hello;

public class Hello{

    private final long id;
    private final String content;

    public Hello(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

構建Controller

經過註解@RestController 聲明一個Restful接口。api

HelloController.javatomcat

@RestController
public class HelloController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/hello")
    public Hellohello(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

入口Main文件

因爲SpringBoot能夠方便的經過jar文件進行交付,經過Main入口文件的配置能夠啓動一個內置的tomcat進行服務實例運行。springboot

@SpringBootApplication
public class Application {

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

至此一個簡單的Restful風格api構建成功,沒有springmvc的xml文件須要配置,很是方便。mvc

maven打包,執行jar包:

java -jar build/libs/gs-rest-service-0.1.0.jarapp

訪問http請求:

http://localhost:8080/greeting

響應結果:

{"id":1,"content":"Hello, World!"}

代碼實例

https://github.com/zhangcj/easymall/tree/master/springbootdemo/springbootdemo-shoppingcart

相關文章
相關標籤/搜索