SpringCloud基本模塊分配搭建以及負載均衡

springcloud是基於springboot的一套微服務的解決方案,springboot能夠快速構建單個應用服務,而springcloud沒有重複造輪子而是將現有的技術(服務發現,負載均衡等)整合到一塊兒提供一套分佈式服務解決方案。java

 

總體的項目結構mysql

以上是整個項目的結構塊web

父類gradle.build引入spring

buildscript {
    ext {
        springBootVersion = '1.5.10.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

subprojects {
    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'

    group = 'com.rk.ytl'
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8

    repositories {
        mavenLocal()
        mavenCentral()
    }


    ext {
        springCloudVersion = 'Edgware.SR3'
    }

    dependencies {
        compile('org.springframework.boot:spring-boot-starter-web')
        compile('org.springframework.cloud:spring-cloud-starter')
//        compile('org.springframework.cloud:spring-cloud-starter-eureka')
//        compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
        runtime('org.springframework.boot:spring-boot-devtools')
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }

    dependencyManagement {
        imports {
            mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
        }
    }
}
View Code

 

 

首先建立註冊中心register-center註冊中心,這裏註冊中心就很少作介紹了。註冊中心的啓動類sql

package com.rk.ytl.register;

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

/**
 * @author 楊天樂
 * @date 2018/3/29 9:59
 */
@SpringBootApplication
@EnableEurekaServer
public class RegisterCenterApplication {

    public static void main(String[] args) {
        SpringApplication.run(RegisterCenterApplication.class,args);
    }
}
View Code

創建註冊中心的配置(application)apache

spring:
  application:
    name: register-center
server:
  port: 8000
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka
    fetch-registry: false
    register-with-eureka: false
View Code

這裏fetch-registry,register-with-eureka必須指定爲false,表名是一個註冊中心api

註冊中心gradle.build 引入springboot

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
}

註冊中心就完成了。mybatis

 

建立業務接口和數據接口,這裏就不作過多的講解了。app

service-api:

package com.rk.ytl.api;

import com.rk.ytl.dto.StudentDTO;
import com.rk.ytl.vo.StudentVO;

import java.util.List;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:18
 */
public interface IStudentService {

    List<StudentDTO> selectAll();

    Integer LoadBalancedPortTest();
}
View Code
package com.rk.ytl.dto;

import java.sql.Date;
import java.util.Objects;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:04
 */
public class StudentDTO {
    private Integer id;
    private String stuName;
    private Integer age;
    private String time;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}
View Code
package com.rk.ytl.vo;

import java.sql.Date;
import java.util.Objects;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:04
 */
public class StudentVO {
    private Integer id;
    private String stuName;
    private Integer age;
    private String time;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}
View Code

project-dao:

package com.rk.ytl.dao.entity;

import org.apache.ibatis.type.Alias;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:04
 */
@Alias("StudentEntity")
public class StudentEntity {
    private Integer id;
    private String stuName;
    private Integer age;
    private String time;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}
View Code
package com.rk.ytl.dao.mapper;

import com.rk.ytl.dao.entity.StudentEntity;

import java.util.List;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:08
 */
public interface StudentMapper {

    List<StudentEntity> selectAll();
}
View Code

project-dao的gradle.build,引入mybatis和springboot的集成jar,已經mysql的jar

dependencies {
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.40'
    compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2'
}
View Code

 

接下來建立Student-service業務模塊

build裏引入project-dao,service-api的依賴

dependencies {
    compile project(':project-dao')
    compile project(':service-api')
    compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
}
View Code

編寫mybatis配置文件,application-local也是以下只是server.port端口不一樣(用於測試負載均衡)

spring:
  application:
    name: Student-service
  datasource:
    url: jdbc:mysql://localhost:3306/myschool?characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
server:
  port: 8001
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka
mybatis:
  type-aliases-package: com.rk.ytl.dao.entity
  mapper-locations: mappers/*.xml
View Code

mappers文件下的studentMapper.xml對應project-dao接口的方法並實現

建立Student-service啓動類

package com.ytl.student;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:17
 */
@SpringBootApplication
@EnableEurekaServer
@MapperScan("com.rk.ytl.dao.mapper")
public class StudentServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentServiceApplication.class,args);
    }
}
View Code

@MapperScan("")對應掃描project-dao的mapper包

建立service包,新建實現業務類

package com.ytl.student.service;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.rk.ytl.api.IStudentService;
import com.rk.ytl.dao.entity.StudentEntity;
import com.rk.ytl.dao.mapper.StudentMapper;
import com.rk.ytl.dto.StudentDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Nullable;
import java.util.List;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:18
 */
@RestController
@Service
public class StudentServiceImpl implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;

    @GetMapping("/selectAll")
    @Override
    public List<StudentDTO> selectAll() {
        return Lists.transform(studentMapper.selectAll(), new Function<StudentEntity, StudentDTO>() {
            @Nullable
            @Override
            public StudentDTO apply(@Nullable StudentEntity input) {
                StudentDTO studentDTO = new StudentDTO();
                BeanUtils.copyProperties(input,studentDTO);
                return studentDTO;
            }
        });
    }

    @Value("${server.port}")
    private Integer port;

    @RequestMapping("/test")
    @Override
    public Integer LoadBalancedPortTest() {
        return port;
    }
}
View Code

最後一個Student-Client用於測試負載均衡

application.yml配置就是最基本的配置發現服務中心

spring:
  application:
    name: Student-Client
server:
  port: 8080
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka
View Code

Student-Client建立啓動類

@LoadBalanced是關鍵,不加,不能實現負載均衡

package com.rk.ytl;

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.web.client.RestTemplate;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:39
 */
@SpringBootApplication
@EnableDiscoveryClient
public class StudentClientApplication {

    @Bean
    @LoadBalanced
    RestTemplate template(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(StudentClientApplication.class,args);
    }
}
View Code

建立controller用於測試

package com.rk.ytl.controller;

import com.rk.ytl.dto.StudentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 楊天樂
 * @date 2018/3/29 10:40
 */
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/test")
    public Integer test(){
        return restTemplate.getForObject("http://STUDENT-SERVICE/test",Integer.class);
    }
}
View Code

url必定要對應業務名稱

gradle.build引入eureka的客戶端

dependencies {
    compile project(':service-api')
    compile('org.springframework.cloud:spring-cloud-starter-eureka')
}
View Code

 

一直訪問localhost:8080/test就能看見端口在切換,實現了負載均衡。

 

學到但願你們給個贊,多評論,謝謝!

相關文章
相關標籤/搜索