SpringBoot+SpringCloud+Ribbon实现负载均衡

1

 

2注册中心配置如下:

server:

  port: 2020



eureka:

  instance:

    hostname: localhost



  client:

    fetch-registry: false

    register-with-eureka: false

    service-url:

      defaultZone:  http://${eureka.instance.hostname}:${server.port}/eureka/

3服务消费者配置如下:

server:

  port: 8082



spring:

  application:

    name: demo_web



eureka:

  client:

    fetch-registry: true    #是否eureka取各微服地址

    register-with-eureka: true    #是否注eureka器

    service-url:

      defaultZone: http://localhost:2020/eureka/

controller如下:

@RestController

@RequestMapping("user")

public class UserController {



    @Autowired

    private UserService userService;



    @RequestMapping("getUserInfo")

    public String getUserInfo(String account, String pwd) {

        System.out.println("务调用者demo_web="+account);

        return userService.getUserInfo(account, pwd);

    }

}

Service如下:

@Service

public class UserService {



    @Autowired

    private RestTemplate restTemplate;



    public String getUserInfo(String account,String pwd) {

        System.out.println("demoservice方法");

        //提供者的用名称进访问

        return restTemplate.getForObject("http://USER-CLIENT/adminControl/getJsp?account="+account+"&pwd="+pwd, String.class);

    }

}

Application如下:

@SpringBootApplication

@EnableEurekaClient

public class DemoWebApplication {



    @Bean

    @LoadBalanced

    public RestTemplate restTemplate() {

        System.out.println("demowebrestTemplate");

        return new RestTemplate();

    }

    

    public static void main(String[] args) {

        System.out.println("demowebmain方法");

        SpringApplication.run(DemoWebApplication.class, args);

    }



}

 

3、两个服务提供者的内容完全一致,只是配置的端口不一致:(一个8080,一个8085)

server:

  port: 8080



spring:

  datasource:

    driver-class-name: com.mysql.jdbc.Driver

    username: root

    password: root

    type: com.alibaba.druid.pool.DruidDataSource

    url: jdbc:mysql://localhost:3306/jx191222

  application:

    name: user-client



mybatis:

  mapper-locations: classpath:mapper/*.xml

  config-location: classpath:SqlMapConfig.xml



eureka:

  client:

    fetch-registry: true   #是否eureka取各微服地址

    register-with-eureka: true  #是否注eureka器

    service-url:

      defaultZone:  http://localhost:2020/eureka

 

4、打开注册中心:

 

5、打开服务消费者端口:

 

6、好像是内部的时间策略机制会自动分配访问哪个端口,实现负载平衡:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值