首先,我们先在C:\Windows\System32\drivers\etc路径下的hosts最后添加两个地址用于模拟服务端以及消费端的IP
127.0.0.1 dept-8001.com #微服务端127.0.0.1 client.com #消费端
SpringCloud的一个最基础Demo,本地真实模拟环境(服务的创建者以及消费者),这是我们Demo截图:
分为一个parent(microcloud),三个Module分别是:microcloud-api,microcloud-consumer-80(消费者),microcloud-provider-dept-8001(服务的提供者)
以下是四个Maven项目各自源码
-
1.microcloud,新建一个pom的maven项目。
pom.xml
<?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.jmx</groupId><artifactId>microcloud</artifactId><version>0.0.1</version><packaging>pom</packaging><name>microcloud</name><url>http://maven.apache.org</url><properties><jdk.version>1.8</jdk.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencyManagement><dependencies><dependency><groupId>com.jmx</groupId><artifactId>microcloud-api</artifactId><version>0.0.1</version></dependency><dependency> <!-- 进行SpringCloud依赖包的导入处理 --><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Dalston.SR1</version><type>pom</type><scope>import</scope></dependency><dependency> <!-- SpringCloud离不开SpringBoot,所以必须要配置此依赖包 --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>1.5.4.RELEASE</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></dependencies></dependencyManagement><build><finalName>microcloud</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>${jdk.version}</source><!-- 源代码使用的开发版本 --><target>${jdk.version}</target><!-- 需要生成的目标class文件的编译版本 --><encode>${project.build.sourceEncoding}</encode></configuration></plugin></plugins></build><modules><module>microcloud-api</module><module>microcloud-provider-dept-8001</module><module>microcloud-consumer-80</module></modules></project>
-
2.microcloud-api,类型为module的maven的项目,这个项目主要就放一些vo类
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><modelVersion>4.0.0</modelVersion><parent><groupId>com.jmx</groupId><artifactId>microcloud</artifactId><version>0.0.1</version></parent><groupId>com.jmx</groupId><artifactId>microcloud-api</artifactId><version>0.0.1</version><name>microcloud-api</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>
Dept.java
package com.jmx.vo;import java.io.Serializable;/**部门VO类* @author JMX**/@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;}@Overridepublic String toString() {return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";}}
数据库创建脚本-8001.sql,使用的是MySQL5.5
DROP DATABASE IF EXISTS "jmx8001" ;CREATE DATABASE jmx8001 CHARACTER SET UTF8 ;USE jmx8001 ;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()) ;
-
3.*microcloud-provider-dept-8001这个是微服务的创建者,在这里我们要将SpringBoot整合Mybatis
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><modelVersion>4.0.0</modelVersion><parent><groupId>com.jmx</groupId><artifactId>microcloud</artifactId><version>0.0.1</version></parent><groupId>com.jmx</groupId><artifactId>microcloud-provider-dept-8001</artifactId><version>0.0.1</version><name>microcloud-provider-dept-8001</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>com.jmx</groupId><artifactId>microcloud-api</artifactId></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-jetty</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></dependencies></project>
Dept_8001_StartSpringCloudApplication.java
package com.jmx.microcloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/**程序主类* @author JMX**/@SpringBootApplicationpublic class Dept_8001_StartSpringCloudApplication {public static void main(String[] args) {SpringApplication.run(Dept_8001_StartSpringCloudApplication.class, args);}}
IDeptDao.java
package com.jmx.microcloud.dao;import java.util.List;import org.apache.ibatis.annotations.Mapper;import com.jmx.vo.Dept;@Mapperpublic interface IDeptDao {public boolean doCreate(Dept vo);public Dept findById(int id);public List<Dept>findAll();}
DeptRest.java
package com.jmx.microcloud.rest;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import com.jmx.microcloud.service.IDeptService;import com.jmx.vo.Dept;@RestControllerpublic class DeptRest {@Autowiredprivate 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();}}
IDeptService.java
package com.jmx.microcloud.service;import java.util.List;import com.jmx.vo.Dept;public interface IDeptService {public Dept get(int id);public boolean add(Dept dept);public List<Dept>list();}
DeptServiceImpl.java
package com.jmx.microcloud.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.jmx.microcloud.dao.IDeptDao;import com.jmx.microcloud.service.IDeptService;import com.jmx.vo.Dept;@Servicepublic class DeptServiceImpl implements IDeptService {@Autowiredprivate IDeptDao ideptdao;@Overridepublic Dept get(int id) {// TODO 自动生成的方法存根return ideptdao.findById(id);}@Overridepublic boolean add(Dept dept) {// TODO 自动生成的方法存根return ideptdao.doCreate(dept);}@Overridepublic List<Dept> list() {// TODO 自动生成的方法存根return ideptdao.findAll();}}
Dept.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.jmx.microcloud.dao.IDeptDao"><select id="findById" resultType="Dept" parameterType="int">SELECT deptno,dname,loc FROM dept WHERE deptno=#{deptno} ;</select><select id="findAll" resultType="Dept">SELECT deptno,dname,loc FROM dept ;</select><insert id="doCreate" parameterType="Dept">INSERT INTO dept(dname,loc) VALUES (#{dname},database()) ;</insert></mapper>
application.yml SpringBoot整合配置文件
server:port: 8001mybatis:config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径type-aliases-package: com.jmx.vo # 定义所有操作类的别名所在包mapper-locations: # 所有的mapper映射文件- classpath:mybatis/mapper/**/*.xmlspring:datasource:type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型driver-class-name: org.gjt.mm.mysql.Driver # 配置MySQL的驱动程序类url: jdbc:mysql://localhost:3307/jmx8001?useUnicode=true&characterEncoding=utf-8 # 数据库连接地址username: root # 数据库用户名password: 123456 # 数据库连接密码dbcp2: # 进行数据库连接池的配置min-idle: 5 # 数据库连接池的最小维持连接数initial-size: 5 # 初始化提供的连接数max-total: 5 # 最大的连接数max-wait-millis: 200 # 等待连接获取的最大超时时间
mybatis.cfg.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <!-- 进行Mybatis的相应的环境的属性定义 --><settings> <!-- 在本项目之中开启二级缓存 --><setting name="cacheEnabled" value="true"/></settings></configuration>
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>
IDeptServiceTest.java,微服务测试类,在这里就不测试了,等会再浏览器里面测试.
package com.jmx.test;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import com.jmx.microcloud.Dept_8001_StartSpringCloudApplication;import com.jmx.microcloud.service.IDeptService;import com.jmx.vo.Dept;@SpringBootTest(classes = Dept_8001_StartSpringCloudApplication.class)@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfigurationpublic class IDeptServiceTest {@Autowiredprivate IDeptService ideptService;@Testpublic void testGet() {System.out.println(ideptService.get(1));}@Testpublic void testAdd() {Dept dept = new Dept() ;dept.setDname("测试部-" + System.currentTimeMillis());System.out.println(ideptService.add(dept));}@Testpublic void testList() {System.out.println(ideptService.list());}}
以上就是微服务的创建项目Demo,我们运行SpringBoot的Dept_8001_StartSpringCloudApplication.java
OK,我们的微服务创建者测试完毕
4.*microcloud-consumer-80这是我们的消费者
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><modelVersion>4.0.0</modelVersion><parent><groupId>com.jmx</groupId><artifactId>microcloud</artifactId><version>0.0.1</version></parent><groupId>com.jmx</groupId><artifactId>microcloud-consumer-80</artifactId><version>0.0.1</version><name>microcloud-consumer-80</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>com.jmx</groupId><artifactId>microcloud-api</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jetty</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></dependencies></project>
Consumer_80_StartSpringCloudApplication.java
package com.jmx.microcloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Consumer_80_StartSpringCloudApplication {public static void main(String[] args) {SpringApplication.run(Consumer_80_StartSpringCloudApplication.class,args);}}
RestConfig.java
package com.jmx.microcloud.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.client.RestTemplate;@Configurationpublic class RestConfig {@Beanpublic RestTemplate getRestTemplate() {return new RestTemplate() ;}}
ConsumerDeptController.java
package com.jmx.microcloud.controller;import java.util.List;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 com.jmx.vo.Dept;@RestControllerpublic 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";@Autowiredprivate 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;}}
application.yml
server:port: 80
这样我们的消费者搭建好了
5.开始测试消费者是否调用微服务
分别运行
都运行成功后
我们看看数据库里是否新增了数据
OK,最基础的Demo已经搭建完成
以上内容转载自https://blog.csdn.net/hsrlzg/article/details/79318312