没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
Spring Cloud多个微服务之间调用代码实例多个微服务之间调用代码实例
主要介绍了Spring Cloud多个微服务之间调用代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者
工作具有一定的参考学习价值,需要的朋友可以参考下
这篇文章主要介绍了Spring Cloud多个微服务之间调用代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具
有一定的参考学习价值,需要的朋友可以参考下
现在又一个学生微服务 user 和 学校微服务 school,如果user需要访问school,我们应该怎么做?
1.使用使用RestTemplate方式方式
添加config
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTempldateConfig {
@Bean
@Scope("singleton")
@LoadBalanced
public RestTemplate restTempldate(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().clear();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return restTemplate;
}
}
@LoadBalanced是一个负载均衡注解,默认是线性轮询策略找到服务
调用:
Result result = restTemplate.postForObject("http://SPRING-SCHOOL/school/findAll", null,Result.class);
return result;
SPRING-SCHOOL 为school应用名称
2.使用使用 openfeign 实现系统见调用实现系统见调用
引入包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
编写调用端代码
import com.lvlvstart.spring.demo.common.entity.School;
import com.lvlvstart.spring.demo.common.msg.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
@FeignClient("SPRING-SCHOOL")
public interface SchoolClient {
@PostMapping(value = "/school/findAll")
public Result<List<School>> findAll();
@PostMapping(value = "/school/findById")
public Result<School> findById(String schoolId);
}
启动类添加注解 @EnableFeignClients
@SpringBootApplication
资源评论
weixin_38689191
- 粉丝: 5
- 资源: 958
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功