微服務之間的調用如何實現(xiàn)
首先 你需要兩個或以上的微服務模塊 至于怎么創(chuàng)建可以參考我上一篇博客 spring cloud eureka注冊中心
如果想在頁面顯示 那么需要先加上
1
|
compile 'org.springframework.boot:spring-boot-starter-thymeleaf' |
這個thymeleaf依賴 springboot推薦使用thymeleaf模板 它的最大好處就是原型即是模板 后綴是html
html文件 需要放在resources/templates文件夾下 因為thymeleaf自動配置的就是這個地址 當然也可以自己改
還需要配置一個屬性
1
2
3
|
spring: thymeleaf: cache: false #開發(fā)時關閉緩存 否則無法看到實時頁面 |
然后在html頁面加上這個
就可以使用thymeleaf模板了
然后在消費端的啟動類中 加上此方法
1
2
3
4
5
6
7
|
@bean // 自動掃描 @loadbalanced //這個注解的意思是在啟動時先加載注冊中心的域名列表 public resttemplate resttemplate() //這個方法用來發(fā)http請求 { resttemplate resttemplate= new resttemplate(); return resttemplate; } |
看一下controller中的代碼
1
2
3
4
5
6
7
8
|
@autowired private resttemplate resttemplate; @requestmapping (value = "index" ) public string toindex(model model){ string msg=resttemplate.getforentity( "http://project-poppy-solr/search" ,string. class ).getbody(); model.addattribute( "msg" ,msg); return "index" ; } |
它的getforentity方法中 傳入的想要調用的方法以及它所在的地址 注意 這里不能直接寫ip地址 必須寫往注冊中心注冊過之后的項目名 要想直接寫項目名必須在啟動類上面的方法中加上@loadbalaced注解
否則ip地址如果發(fā)生變化 就需要更改 特別麻煩 作為一個優(yōu)秀的程序員 當然是不能這么干的
然后把它放到model中發(fā)到頁面 就可以調用另一個微服務的方法 實現(xiàn)了微服務間的調用
還有一個調用的方法是feign 以后會講解
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/wangkee/p/9305134.html