zoukankan      html  css  js  c++  java
  • spring cloud 微服务应用间通讯

    SpringCloud 应用间通信基于HTTP的Restful调用方式有两种,RestTemplate与Feign。

    1.RestTemplate应用间通讯

    通过 @LoadBalanced,可在restTemplate 直接使用应用名字。

    @Component
    public class RestTemplateConfig {
    
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
        
    }
    
        @Autowired
        private RestTemplate restTemplate;
        
        @Override
        public String hello() {
            //使用RestTemplate通讯调用auth-server服务
            String url="http://auth-server/hello";
            //返回值类型和我们的业务返回值一致
            return restTemplate.getForObject(url, String.class);
        }

    2.Feign应用间通讯

    引入依赖注意要加版本号,否则引入依赖可能失败

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
        <version>1.4.2.RELEASE</version>
    </dependency>

    启动类需要增加注解@EnableFeignClients

    @EnableFeignClients
    @EnableEurekaClient
    @SpringBootApplication
    public class ManagerServerApplication {
        public static void main(String[] args) {
            SpringApplication.run(ManagerServerApplication.class, args);
        }
    }

    需要编写接口声明
    @FeignClient参数注解表明这个是Fegin客户端,name参数指定访问的服务网关

    @FeignClient(name = "auth-server")//服务网关
    public interface TestClient {
    
        @RequestMapping("/fegin/hello")//调用的服务
        String feginHello();
    }

    调用

        @Autowired
        private TestClient testClient;
    
        @Override
        public String feginHello() {
            //使用fegin通讯调用auth-server服务
            return testClient.feginHello();
        }
  • 相关阅读:
    C# Log4.Net日志组件的应用系列(二)
    C# Log4.Net日志组件的应用系列(一)
    使用TFS+GIT实现分布式项目管理
    动软代码生成器使用教程
    SVN使用教程
    windows系统重装流程
    使用纯真IP库获取用户端地理位置信息
    使用扩展方法重写.NET底层架构
    使用单例模式创建模型仓储层的唯一调用
    使用SQL Delta.v5.1.1.98.破解版同步数据结构
  • 原文地址:https://www.cnblogs.com/jtnote/p/10370717.html
Copyright © 2011-2022 走看看