SpringCloud学习之路(一)-简单Demo

首先,我们先在C:\Windows\System32\drivers\etc路径下的hosts最后添加两个地址用于模拟服务端以及消费端的IP

127.0.0.1	dept-8001.com   #微服务端
127.0.0.1	client.com      #消费端

SpringCloud的一个最基础Demo,本地真实模拟环境(服务的创建者以及消费者),这是我们Demo截图:

SpringCloud学习之路(一)-简单Demo_第1张图片

分为一个parent(microcloud),三个Module分别是:microcloud-api,microcloud-consumer-80(消费者),microcloud-provider-dept-8001(服务的提供者)

以下是四个Maven项目各自源码

1.microcloud,新建一个pom的maven项目。

SpringCloud学习之路(一)-简单Demo_第2张图片

pom.xml



	  4.0.0
	  com.jmx
	  microcloud
	  0.0.1
	  pom
	  	microcloud
		http://maven.apache.org
	
		1.8
		UTF-8
	
	
		
			
				com.jmx
				microcloud-api
				0.0.1
			

				
				org.springframework.cloud
				spring-cloud-dependencies
				Dalston.SR1
				pom
				import
			
				
				org.springframework.boot
				spring-boot-dependencies
				1.5.4.RELEASE
				pom
				import
			
			
				mysql
				mysql-connector-java
				5.0.4
			
			
				com.alibaba
				druid
				1.0.31
			
			
				org.mybatis.spring.boot
				mybatis-spring-boot-starter
				1.3.0
			
		
	
	
		microcloud
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				
					${jdk.version}
					${jdk.version}
					${project.build.sourceEncoding}
				
			
		
	
	
		microcloud-api
		microcloud-provider-dept-8001
    microcloud-consumer-80
  

2.microcloud-api,类型为module的maven的项目,这个项目主要就放一些vo类

SpringCloud学习之路(一)-简单Demo_第3张图片

pom.xml



  4.0.0
  
    com.jmx
    microcloud
    0.0.1
  
  com.jmx
  microcloud-api
  0.0.1
  microcloud-api
  http://maven.apache.org
  
    UTF-8
  

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;
    }
    @Override
    public 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

SpringCloud学习之路(一)-简单Demo_第4张图片

pom.xml



  4.0.0
  
    com.jmx
    microcloud
    0.0.1
  
  com.jmx
  microcloud-provider-dept-8001
  0.0.1
  microcloud-provider-dept-8001
  http://maven.apache.org
  

		UTF-8
	
	
		
			com.jmx
			microcloud-api
		
		
			junit
			junit
			test
		
		
			mysql
			mysql-connector-java
		
		 
			com.alibaba
			druid
		
		
			ch.qos.logback
			logback-core
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
		
		
			org.springframework.boot
			spring-boot-starter-jetty
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework
			springloaded
		
		
			org.springframework.boot
			spring-boot-devtools
		
	

Dept_8001_StartSpringCloudApplication.java

package com.jmx.microcloud;

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

/**程序主类
 * @author JMX
 *
 */
@SpringBootApplication
public 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;
@Mapper
public interface IDeptDao {
    public boolean doCreate(Dept vo);
    public Dept findById(int id);
    public ListfindAll();

}

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;

@RestController
public class DeptRest {
    
    @Autowired
    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 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 Listlist();

}

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;

@Service
public class DeptServiceImpl implements IDeptService {
    
    @Autowired
    private IDeptDao ideptdao;

    @Override
    public Dept get(int id) {
	// TODO 自动生成的方法存根
	return ideptdao.findById(id);
    }

    @Override
    public boolean add(Dept dept) {
	// TODO 自动生成的方法存根
	return ideptdao.doCreate(dept);
    }

    @Override
    public List list() {
	// TODO 自动生成的方法存根
	return ideptdao.findAll();
    }

}

Dept.xml




	
	
	
		INSERT INTO dept(dname,loc) VALUES (#{dname},database()) ;
	

application.yml     SpringBoot整合配置文件

server:
  port: 8001
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml    # mybatis配置文件所在路径
  type-aliases-package: com.jmx.vo                      # 定义所有操作类的别名所在包
  mapper-locations:                                     # 所有的mapper映射文件
  - classpath:mybatis/mapper/**/*.xml
spring:
  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



 
		
		
	

logback.xml




	
	
	
		
			%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n
		
	
	
		${LOG_HOME}/${APP}_detail.log
		
			%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n
		
		
			${LOG_HOME}/${APP}_detail.log.%d{yyyyMMdd}
		
	
	
		${LOG_HOME}/${APP}_access.log
		
			%d{yy-MM-dd.HH:mm:ss.SSS};%X{ServiceId};%m%n
		
		
			${LOG_HOME}/${APP}_access.log.%d{yyyyMMdd}
		
	


	
		
	
	
	

	
		
		
	

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)
@WebAppConfiguration
public class IDeptServiceTest {
    
    @Autowired
    private  IDeptService ideptService;

	@Test
	public void testGet() {
		System.out.println(ideptService.get(1));
	}

	@Test
	public void testAdd() {
		Dept dept = new Dept() ;
		dept.setDname("测试部-" + System.currentTimeMillis());
		System.out.println(ideptService.add(dept)); 
	}

	@Test
	public void testList() {
		System.out.println(ideptService.list());
	}

}

以上就是微服务的创建项目Demo,我们运行SpringBoot的Dept_8001_StartSpringCloudApplication.java



OK,我们的微服务创建者测试完毕


4.*microcloud-consumer-80这是我们的消费者

SpringCloud学习之路(一)-简单Demo_第5张图片

pom.xml



  4.0.0
  
    com.jmx
    microcloud
    0.0.1
  
  com.jmx
  microcloud-consumer-80
  0.0.1
  microcloud-consumer-80
  http://maven.apache.org
	
    UTF-8
  	
 	
		
			com.jmx
			microcloud-api
		
		
			junit
			junit
			test
		
		
			org.springframework.boot
			spring-boot-starter-jetty
		
		
			org.springframework.boot
			spring-boot-starter-web
        	
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework
			springloaded
		
		
			org.springframework.boot
			spring-boot-devtools
		
	


Consumer_80_StartSpringCloudApplication.java

package com.jmx.microcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public 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;

@Configuration
public class RestConfig {
	@Bean
	public 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;



@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 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.开始测试消费者是否调用微服务

分别运行

SpringCloud学习之路(一)-简单Demo_第6张图片

都运行成功后

SpringCloud学习之路(一)-简单Demo_第7张图片




我们看看数据库里是否新增了数据

SpringCloud学习之路(一)-简单Demo_第8张图片

OK,最基础的Demo已经搭建完成

你可能感兴趣的:(SpringClond)