栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring-Cloud之Eurka微服务注册中心集群和Ribbon负载均衡的搭建

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring-Cloud之Eurka微服务注册中心集群和Ribbon负载均衡的搭建

文章目录
  • 说明:
  • springcloud-api的搭建
  • springcloud-consumer-dept-80消费者的搭建
    • application.yaml
    • RestTemplateConfig
    • ConsumerDept
    • Consumer
  • springcloud-enureka-7001集群的搭建
    • 依赖
    • EurekaServerPort7001
    • application.yaml
  • springcloud-enureka-7002集群的搭建
    • application.yaml
  • springcloud-enureka-7003集群的搭建
    • application.yaml
  • springcloud-provider-dept-8001生产者的搭建
    • DeptController
    • DeptMapper
    • DeptService
    • DeptServiceImpl
    • Provider
    • DeptMapper.xml
    • mybatis-config.xml
    • application.yaml
    • pom
  • 整个项目的pom文件

说明:

本案例是依靠狂神说springcloud讲解完成,对于添加部门接口在测试的时候,使用了post请求,添加未成功,其他功能没有问题。

http://localhost/consumer/dept/add?dname=%27aa%27
问题描述:在生产者方,添加接口没有问题,在消费者使用RestTemplate调用postForObject的方法,报错如下,eureka集群添加部门名称功能有问题,解决方案正在处理中。

springcloud-api的搭建

  • 主要是封装实体类,添加mysql-connector-java的依赖。
  • 导入依赖
    
        
            org.projectlombok
            lombok
        
        
            mysql
            mysql-connector-java
        
    
  • java实体类
package cn.itcast.springcloud.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;


@Accessors
@NoArgsConstructor
@Data
public class Dept implements Serializable {
    private long deptno;
    private String dname;
    private String DB_source;

    public Dept(String dname) {
        this.dname = dname;
    }
}

springcloud-consumer-dept-80消费者的搭建
  • 消费者中配备了Eurka的服务注册中心 和 Ribbon 的负载均衡
application.yaml
server:
  port: 80

eureka:
  client:
    register-with-eureka: true   #表示是否将自己注册进Eureka默认为true
    fetch-registry: true  #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用 负载均衡
    service-url:
      defaultZone: http://localhost01:7001/eureka/,http://localhost02:7002/eureka/,http://localhost03:7003/eureka/
spring:
  application:
    name: consumer
RestTemplateConfig
package cn.itcast.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;


@Configuration
public class RestTemplateConfig {
    @Bean
    @LoadBalanced  //Ribbon的负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}
ConsumerDept
package cn.itcast.controller;

import cn.itcast.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@RestController
public class ConsumerDept {
   // private static final String PROVIDERDEPT = "http://localhost:8001";
    private static final String PROVIDERDEPT ="http://SPRINGCLOUD-PROVIDER-DEPT";
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/dept/all")
    public List findAllDept() {
        return restTemplate.getForObject(PROVIDERDEPT+"dept/all", List.class);
    }

//测试有问题,可删除
    @RequestMapping("/consumer/dept/add")
    public boolean add( @RequestBody Dept dept) {
        return restTemplate.postForObject(PROVIDERDEPT+"dept/add", dept, Boolean.class);
    }

    @GetMapping("/consumer/dept/get/{deptno}")
    public Dept findById(@PathVariable("deptno") long deptno) {
       return restTemplate.getForObject(PROVIDERDEPT+"/dept/get/"+deptno, Dept.class);
    }
}

Consumer
package cn.itcast;

import cn.itcast.config.RestTemplateConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;



@SpringBootApplication
@EnableEurekaClient
//@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = RestTemplateConfig.class)
public class Consumer {
    public static void main(String[] args) {
        SpringApplication.run(Consumer.class,args);
    }
}

springcloud-enureka-7001集群的搭建

依赖

            org.springframework.boot
            spring-boot-devtools
            2.1.4.RELEASE
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka-server
            1.4.6.RELEASE
        
EurekaServerPort7001
package cn.itcast.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;


@SpringBootApplication
@EnableEurekaServer
public class EurekaServerPort7001 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerPort7001.class,args);
    }
}
application.yaml
server:
  port: 7001

eureka:
  instance:
    hostname: localhost01 #eureka的名称
  client:
    fetch-registry: false #是否将自己作为erueka的注册中心
    register-with-eureka: false #是否将自己注册到eureka中
    service-url:
      defaultZone: http://localhost02:7002/eureka/,http://localhost03:7003/eureka/
  server:
    # 关闭自我保护机制,保证不可用的服务被及时剔除
    enable-self-preservation: false
    # 如果2秒内没有收到某个微服务的心跳,那就剔除该微服务,单位为毫秒
    eviction-interval-timer-in-ms: 2000


springcloud-enureka-7002集群的搭建

application.yaml
server:
  port: 7002

eureka:
  instance:
    hostname: localhost02 #eureka的名称
  client:
    fetch-registry: false #是否将自己作为erueka的注册中心
    register-with-eureka: false #是否将自己注册到eureka中
    service-url:
      defaultZone: http://localhost01:7001/eureka/,http://localhost03:7003/eureka/
  server:
    # 关闭自我保护机制,保证不可用的服务被及时剔除
    enable-self-preservation: false
    # 如果2秒内没有收到某个微服务的心跳,那就剔除该微服务,单位为毫秒
    eviction-interval-timer-in-ms: 2000


  • 配置文件不同,名称不同,其他与springcloud-enureka-7001完全相同
springcloud-enureka-7003集群的搭建

application.yaml
server:
  port: 7003

eureka:
  instance:
    hostname: localhost03 #eureka的名称
  client:
    fetch-registry: false #是否将自己作为erueka的注册中心
    register-with-eureka: false #是否将自己注册到eureka中
    service-url:
      defaultZone: http://localhost01:7001/eureka/,http://localhost02:7002/eureka/
  server:
    # 关闭自我保护机制,保证不可用的服务被及时剔除
    enable-self-preservation: false
    # 如果2秒内没有收到某个微服务的心跳,那就剔除该微服务,单位为毫秒
    eviction-interval-timer-in-ms: 2000


  • 配置文件不同,名称不同,其他与springcloud-enureka-7001完全相同
springcloud-provider-dept-8001生产者的搭建

DeptController
package cn.itcast.controller;

import cn.itcast.service.DeptService;
import cn.itcast.springcloud.pojo.Dept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    //获取一些配置的信息
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/dept/all")
    public List findAllDept() {
        return deptService.findAllDept();
    }

    @RequestMapping("/dept/add")
    public Boolean addDept(Dept dept) {
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{deptno}")
    public Dept findById(@PathVariable("deptno") long deptno) {
        return deptService.findById(deptno);
    }

//    @GetMapping("dept/discover")
//    public Object discover() {
//        List services = discoveryClient.getServices();
//        System.out.println("微服务信息" + services);
//
//        List instances = discoveryClient.getInstances("springcloud-provider-dept");
//        for (ServiceInstance instance : instances) {
//            System.out.println(
//                    instance.getHost() + "t" +
//                            instance.getUri() + "t" +
//                            instance.getPort() + "t" +
//                            instance.getServiceId()
//            );
//
//        }
//        return discoveryClient;
//    }
}

DeptMapper
package cn.itcast.mapper;

import cn.itcast.springcloud.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;


@Mapper
@Repository
public interface DeptMapper {

    public List findAllDept();

    public Boolean addDept(Dept dept);

    public Dept findById(long deptno);
}

DeptService
package cn.itcast.service;

import cn.itcast.springcloud.pojo.Dept;

import java.util.List;

public interface DeptService {
    public List findAllDept();

    public Boolean addDept(Dept dept);

    public Dept findById(long deptno);
}

DeptServiceImpl
package cn.itcast.service.impl;

import cn.itcast.mapper.DeptMapper;
import cn.itcast.service.DeptService;
import cn.itcast.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Override
    public List findAllDept() {
        return deptMapper.findAllDept();
    }

    @Override
    public Boolean addDept(Dept dept) {
        return deptMapper.addDept(dept);
    }
    @Override
    public Dept findById(long deptno) {
        return deptMapper.findById(deptno);
    }
}

Provider
package cn.itcast;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;


@SpringBootApplication
@EnableEurekaClient//将服务注入进来
//@EnableDiscoveryClient//服务发现
public class Provider {
    public static void main(String[] args) {
        SpringApplication.run(Provider.class,args);
    }
}

DeptMapper.xml



   
       select * from dept
   

    
        insert into dept (dname,DB_source) values (#{dname},DATAbase())
    
   


mybatis-config.xml



    
        
    


application.yaml
server:
  port: 8001
mybatis:
  type-aliases-package: cn.itcast.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml



spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db01?useSSL=true&useUnicode=true&characterEncoding=utf8
    username: root
    password: 1234

eureka:
  client:
    #表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用 负载均衡
    fetch-registry: true
    service-url:
      #注册中心地址    如果集群每个Eureka注册中心都写上用,间隔
      defaultZone: http://localhost01:7001/eureka/,http://localhost02:7002/eureka/,http://localhost03:7003/eureka/

pom


    
        springcloud-demo01
        cn.itcast
        1.0-SNAPSHOT
    
    4.0.0

    springcloud-provider-dept-8001

    
        8
        8
    

    
        org.springframework.cloud
        spring-cloud-starter-eureka
        1.4.6.RELEASE
    

    
        org.springframework.boot
        spring-boot-starter-actuator
    
    
        cn.itcast
        springcloud-api
        1.0-SNAPSHOT
    
    
        junit
        junit
    
    
        mysql
        mysql-connector-java
    
    
        ch.qos.logback
        logback-core
    
    
        com.alibaba
        druid
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
    

    
        org.springframework.boot
        spring-boot-starter-test
    
    
        org.springframework.boot
        spring-boot-starter-web
        2.1.5.RELEASE
    





    
        org.springframework.boot
        spring-boot-devtools
    


整个项目的pom文件


    4.0.0

    cn.itcast
    springcloud-demo01
    pom
    1.0-SNAPSHOT
    
        springcloud-api
        springcloud-provider-dept-8001
        springcloud-consumer-dept-80
        springcloud-enureka-7001
        springcloud-enureka-7002
        springcloud-enureka-7003
    

    
        8
        8
        4.12
        1.2.17
        1.16.18
    

    
        
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                Greenwich.SR1
                pom
                import
            
            
            
                org.springframework.boot
                spring-boot-dependencies
                2.1.0.RELEASE
                pom
                import
            
            
            
                mysql
                mysql-connector-java
                5.1.47
            
            
            
                com.alibaba
                druid
                1.1.10
            
            
            
                org.mybatis.spring.boot
                mybatis-spring-boot-starter
                1.3.2
            
            
            
                ch.qos.logback
                logback-core
                1.2.3
            
            
            
                junit
                junit
                ${junit.version}
            
            
            
                log4j
                log4j
                ${log4j.version}
            
            
            
                org.projectlombok
                lombok
                ${lombok.version}
            
        
    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/343358.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号