1. 程式人生 > >SpringCloud學習筆記一,(服務端, 消費端), 硬編碼級別

SpringCloud學習筆記一,(服務端, 消費端), 硬編碼級別

1. 建立maven父工程microcloud, 管理依賴,

    建立microcloud-api模組, 存放entity類和sql, 

    建立microcloud-provider-dept-8001模組,服務端, 

    建立microcloud-consumer-80模組, 消費端

2. microcloud的pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sedin</groupId>
    <artifactId>microcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>microcloud</name>
    <description>SpringCloud測試demo</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>

            <!--springboot啟動類-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>

            <!-- 進行SpringCloud依賴包的匯入處理 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.0.4</version>
            </dependency>

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.0.31</version>
            </dependency>

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>

            <!--spring-loaded實現熱部署-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
                <version>1.3.0.RELEASE</version>
            </dependency>

            <!--Springsecurity給服務端提供安全訪問-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
                <version>2.0.2.RELEASE</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>microcloud</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source><!-- 原始碼使用的開發版本 -->
                    <target>${java.version}</target><!-- 需要生成的目標class檔案的編譯版本 -->
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <modules>
        <module>microcloud-api</module>
        <module>microcloud-consumer-80</module>
        <module>microcloud-provider-dept-8001</module>
    </modules>

</project>

3. microcloud-api的構建

Dept程式碼

package com.sedin.microcloudapi;

import java.io.Serializable;

/**
 * @Description:部門類
 * @Author: 陳歡
 * @Date: 2018/10/8 13:53
 */
@SuppressWarnings("serial")
public class Dept implements Serializable {

    private Long deptno;
    private String dname;
    private String loc;

    public Long getDeptno() {
        return deptno;
    }

    public void setDeptno(Long deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
}

資料庫建立指令碼_8001.sql

DROP DATABASE IF EXISTS "cloud";
CREATE DATABASE cloud CHARACTER SET UTF8 ;
USE cloud ;
CREATE TABLE dept (
  deptno		BIGINT		AUTO_INCREMENT ,	dname		VARCHAR(50) ,
  	loc			VARCHAR(50) ,	CONSTRAINT pk_deptno PRIMARY KEY(deptno)
  	) ;
INSERT INTO dept(dname,loc) VALUES ('開發部',database()) ;
INSERT INTO dept(dname,loc) VALUES ('財務部',database()) ;
INSERT INTO dept(dname,loc) VALUES ('市場部',database()) ;
INSERT INTO dept(dname,loc) VALUES ('後勤部',database()) ;
INSERT INTO dept(dname,loc) VALUES ('公關部',database()) ;

4. microcloud-provider-dept-8001構建

目錄結構

pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.sedin</groupId>
        <artifactId>microcloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>microcloud-provider-dept-8001</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>microcloud-provider-dept-8001</name>
    <description>Demo project for Spring Boot</description>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sedin</groupId>
            <artifactId>microcloud-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!--Springsecurity給服務端提供安全訪問-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

dao層IDeptDao

package com.sedin.microcloudproviderdept8001.dao;

import com.sedin.microcloudapi.Dept;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @Description:
 * @Auther: 陳歡
 * @Date: 2018/10/8 14:08
 */
@Mapper
public interface IDeptDao {

    @Insert("INSERT INTO dept(dname,loc) VALUES (#{dname},database());")
    public boolean doCreate(Dept vo);

    @Select("SELECT deptno,dname,loc FROM dept WHERE deptno=#{deptno};")
    public Dept findById(@Param("deptno") int id);

    @Select("SELECT deptno,dname,loc FROM dept;")
    public List<Dept> findAll();

}

service層IDeptService

package com.sedin.microcloudproviderdept8001.service;

import com.sedin.microcloudapi.Dept;

import java.util.List;

/**
 * @Description:
 * @Author: 陳歡
 * @Date: 2018/10/8 14:09
 */
public interface IDeptService {
    public Dept get(int id);

    public boolean add(Dept dept);

    public List<Dept> list();

}

service.impl層DeptServiceImpl

package com.sedin.microcloudproviderdept8001.service.impl;

import com.sedin.microcloudapi.Dept;
import com.sedin.microcloudproviderdept8001.dao.IDeptDao;
import com.sedin.microcloudproviderdept8001.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Auther: 陳歡
 * @Date: 2018/10/8 14:09
 */
@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private IDeptDao ideptdao;

    @Override
    public Dept get(int id) {
        return ideptdao.findById(id);
    }

    @Override
    public boolean add(Dept dept) {
        return ideptdao.doCreate(dept);
    }

    @Override
    public List<Dept> list() {
        return ideptdao.findAll();
    }


}

rest層DeptRest

package com.sedin.microcloudproviderdept8001.rest;

import com.sedin.microcloudapi.Dept;
import com.sedin.microcloudproviderdept8001.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Description:
 * @Auther: 陳歡
 * @Date: 2018/10/8 14:08
 */
@RestController
public class DeptRest {

    @Resource
    private IDeptService iDeptService;

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    public Dept get(@PathVariable(value = "id") int id) {
        return iDeptService.get(id);
    }

    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public boolean add(@RequestBody Dept dept) {
        return iDeptService.add(dept);
    }

    @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
    public List<Dept> list() {
        return iDeptService.list();
    }

}

啟動類MicrocloudProviderDept8001Application

package com.sedin.microcloudproviderdept8001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MicrocloudProviderDept8001Application {

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

application.yml

server:
  port: 8001
#資料來源配置
mybatis:
  #  config-location: classpath:mybatis/mybatis.cfg.xml
  type-aliases-package: com.sedin.microcloudapi
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    dbcp2:
      min-idle: 5
      initial-size: 5
      max-total: 5
      max-wait-millis: 200
  security:                       #  springSecurity的安全配置
    user:
      name: chenhuan
      password: chenhuan123!
      roles: -USER
logging:
  level:
    com.sedin.microcloudproviderdept8001.dao: debug

logback.xml

<?xml version="1.0" encoding="UTF-8" ?>

<configuration scan="true">
    <property name="APP" value="${project.artifactId}"/>
    <property name="LOG_HOME" value="/data/www/log/${APP}"/>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n</pattern>
        </encoder>
    </appender>
    <appender name="DETAIL" class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
        <File>${LOG_HOME}/${APP}_detail.log</File>
        <encoder>
            <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP}_detail.log.%d{yyyyMMdd}</fileNamePattern>
        </rollingPolicy>
    </appender>
    <appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
        <File>${LOG_HOME}/${APP}_access.log</File>
        <encoder>
            <pattern>%d{yy-MM-dd.HH:mm:ss.SSS};%X{ServiceId};%m%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP}_access.log.%d{yyyyMMdd}</fileNamePattern>
        </rollingPolicy>
    </appender>
    <logger name="ACCESS">
        <appender-ref ref="ACCESS"/>
    </logger>
    <logger name="druid.sql.Statement" level="DEBUG"/>
    <logger name="com.jmx.microcloud.dao" level="TRACE"/>
    <root level="INFO">
        <appender-ref ref="DETAIL"/>
        <appender-ref ref="CONSOLE"/>
    </root>
</configuration>


至此, 我們的服務端microcloud-provider-dept-8001就搭建好了, 啟動之後在瀏覽器輸入http://localhost:8001/dept/list/

因為我們使用了springsecurity做許可權控制, 此時需要我們輸入在application.yml配置的使用者名稱和密碼登陸

5. 搞到這裡已經略微疲憊了, 就差一個消費端了, 馬上就過去了, microcloud-consumer-80構建

目錄結構

pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.sedin</groupId>
        <artifactId>microcloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>microcloud-consumer-80</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>microcloud-consumer-80</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sedin</groupId>
            <artifactId>microcloud-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

application.yml

server:
  port: 80

啟動類MicrocloudConsumer80Application

package com.sedin.microcloudconsumer80;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class MicrocloudConsumer80Application {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

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

controller層的ConsumerDeptController

package com.sedin.microcloudconsumer80.controller;

import com.sedin.microcloudapi.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Description:
 * @Author: 陳歡
 * @Date: 2018/10/8 15:54
 */
@RestController
public class ConsumerDeptController {
    public static final String DEPT_GET_URL = "http://dept-8001.com:8001/dept/get/";
    public static final String DEPT_LIST_URL = "http://dept-8001.com:8001/dept/list/";
    public static final String DEPT_ADD_URL = "http://dept-8001.com:8001/dept/add";
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/dept/get")
    public Object getDept(long id) {
        Dept dept = restTemplate.getForObject(DEPT_GET_URL + id, Dept.class);
        return dept;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/consumer/dept/list")
    public Object listDept() {
        List<Dept> allDepts = this.restTemplate.getForObject(DEPT_LIST_URL, List.class);
        return allDepts;
    }

    @RequestMapping(value = "/consumer/dept/add")
    public Object addDept(Dept dept) {
        Boolean flag = this.restTemplate.postForObject(DEPT_ADD_URL, dept, Boolean.class);
        return flag;
    }


}

6. 離結束僅差一步, 為方便測試, 我們在本機的hosts檔案中配置一下虛擬域名

到了此時我們發現並沒有使用springcloud的任何牛逼有名的元件啊, 包括Eureka, feign, ribbon等等, 包括呼叫服務端的資料都是用硬編碼實現的. 下面做一下修改來試試Eureka這個牛逼的元件如何應用到專案裡面