当前位置: 移动技术网 > IT编程>开发语言>Java > spring cloud eureka微服务之间的调用详解

spring cloud eureka微服务之间的调用详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

微服务之间的调用如何实现

首先 你需要两个或以上的微服务模块 至于怎么创建可以参考我上一篇博客

如果想在页面显示 那么需要先加上

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 以后会讲解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网