微服務之間的調用如何實現
首先 你需要兩個或以上的微服務模塊 至於怎么創建可以參考我上一篇博客 spring cloud eureka注冊中心
如果想在頁面顯示 那么需要先加上
compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
這個thymeleaf依賴 springboot推薦使用thymeleaf模板 它的最大好處就是原型即是模板 后綴是html
html文件 需要放在resources/templates文件夾下 因為thymeleaf自動配置的就是這個地址 當然也可以自己改
還需要配置一個屬性
spring: thymeleaf: cache: false #開發時關閉緩存 否則無法看到實時頁面
然后在html頁面加上這個
就可以使用thymeleaf模板了
然后在消費端的啟動類中 加上此方法
@Bean // 自動掃描 @LoadBalanced //這個注解的意思是在啟動時先加載注冊中心的域名列表 public RestTemplate restTemplate() //這個方法用來發http請求 { RestTemplate restTemplate=new RestTemplate(); return restTemplate; }
看一下controller中的代碼
@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地址如果發生變化 就需要更改 特別麻煩 作為一個優秀的程序員 當然是不能這么干的
然后把它放到model中發到頁面 就可以調用另一個微服務的方法 實現了微服務間的調用
還有一個調用的方法是feign 以后會講解