zoukankan      html  css  js  c++  java
  • spring boot 2.0 ribbon 负载均衡配置

    1.pom.xml

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
                <version>2.0.2.RELEASE</version>
            </dependency>

    2.入口文件:UserConsumerDemoApplication.java   

    package cn.itcast.user;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
    import org.springframework.web.client.RestTemplate;
    
    @EnableDiscoveryClient
    @SpringBootApplication
    public class UserConsumerDemoApplication {
    
        @Bean
        @LoadBalanced  //负载均衡
        public RestTemplate restTemplate() {
            // 这次我们使用了OkHttp客户端,只需要注入工厂即可
            return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        }
    
        public static void main(String[] args) {
            SpringApplication.run(UserConsumerDemoApplication.class, args);
        }
    }

    3.UserRibbonController.java

    package cn.itcast.user.controller;
    
    import cn.itcast.user.pojo.User;
    import com.netflix.ribbon.Ribbon;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.client.discovery.DiscoveryClient;
    import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("consumerRobbon")
    public class UserRobbonController {
        @Autowired
        private RestTemplate restTemplate;
    
        @GetMapping("{id}")
        public User queryUserById(@PathVariable("id") Long id){
    
            String url = "http://user-service/user/" + id;
            User user = restTemplate.getForObject(url, User.class);
            return  user;
        }
    }
  • 相关阅读:
    css position 和 块级/行内元素解释
    jquery.cookie.js $.cookie()是怎么使用
    css transition transform animation例子讲解
    HttpUrlConnection使用详解--转
    HttpURLConnection与HttpClient浅析---转
    java对含有中文的字符串进行Unicode编码
    VMWARE里安装时出现'SMBus Host Controller not enabled'
    消息队列 Kafka 的基本知识及 .NET Core 客户端
    安装和测试Kafka
    mongo 聚合函数
  • 原文地址:https://www.cnblogs.com/wuxiang12580/p/10785671.html
Copyright © 2011-2022 走看看