SpringCloud入门 - 业务模块搭建(二)

SpringCloud入门 - 业务模块搭建

1. 需求

搭建业务模块,实现Emp员工信息操作

2. 工程结构示意

SpringCloud入门 - 业务模块搭建(二)_第1张图片
模块总览
SpringCloud入门 - 业务模块搭建(二)_第2张图片

3. 父工程

3.1 创建maven项目

SpringCloud入门 - 业务模块搭建(二)_第3张图片

3.2 pom配置


<parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.0.8.RELEASEversion>
    <relativePath />
parent>

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

<dependencyManagement>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-dependenciesartifactId>
            <version>Finchley.SR2version>
            <type>pomtype>
            <scope>importscope>
        dependency>
    dependencies>
dependencyManagement>


<dependencies>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starterartifactId>
    dependency>
	
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-configartifactId>
    dependency>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>
    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>springloadedartifactId>
        <version>1.2.8.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-devtoolsartifactId>
    dependency>
dependencies>

4. 公共模块构建

4.1 New Maven Project

创建maven项目emall-api,该项目无需继承刚刚创建的父项目

4.2 pom配置

<dependencies>
	
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
    dependency>
dependencies>

4.3 创建员工Entity

@SuppressWarnings("serial")
@NoArgsConstructor
@Data
@Accessors(chain=true)//开启链式风格
public class Emp implements Serializable{
	private Integer empNo;
	private String name;
	private String sex;
	private Integer age;
	private Double sal;
	private String dbSource;
}

5. 员工模块服务提供者构建

5.1 New Maven Module

SpringCloud入门 - 业务模块搭建(二)_第4张图片
SpringCloud入门 - 业务模块搭建(二)_第5张图片

创建后观察下父工程的pom内容。

5.2 pom配置

<dependencies>
    
    <dependency>
        <groupId>com.kgcgroupId>
        <artifactId>emall-apiartifactId>
        <version>0.0.1-SNAPSHOTversion>
    dependency>

    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.1.10version>
    dependency>
    
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <scope>runtimescope>
    dependency>

    
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>1.3.0version>
    dependency>

    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-jettyartifactId>
    dependency>

    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
        
        <exclusions>  
            <exclusion>  
                <groupId>org.springframework.bootgroupId>  
                <artifactId>spring-boot-starter-tomcatartifactId>  
            exclusion>  
        exclusions>  
    dependency>
dependencies>

(可以把依赖的版本号放到父项目中的dependencyManagement统一管理)

5.3 application.yml配置

在resource目录下新建application.yml并编辑yml内容

server:
  port: 8001                        #服务端口
  
spring:
  application:
    name: emall-emp-provider        #服务名
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource  #数据源操作类型
    driver-class-name: com.mysql.jdbc.Driver      #mysql驱动类
    url: jdbc:mysql://localhost:3306/empdb01      #数据库名称
    username: root                                #数据库连接用户
    password: 123456                              #数据库连接密码
    dbcp2:
      initial-size: 5                             #连接池初始化连接数
      min-idle: 5                                 #连接池最少连接数
      max-idle: 5                                 #连接池最大连接数
      max-wait-millis: 300                        #连接最大等待超时时间
    
  
# mybatis整合
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml    #mybatis配置文件的位置
  type-aliases-package: com.emall.entities              #为Entity包配置别名
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml                   #mapper映射文件的位置

5.4 mybatis.cfg.xml配置

  1. 新建mybatis.cfg.xml,注意路径和文件名和上面yml中定义保持一致
  2. 编辑内容,主要是配置二级缓存(如果不开启二级缓存,这个文件可以省略)


<configuration>
	<settings>
		
		<setting name="cacheEnabled" value="true" />
	settings>
configuration>

5.5 建库建表

DROP DATABASE IF EXISTS empdb01;
CREATE DATABASE empdb01 CHARACTER SET UTF8;
USE empdb01;

CREATE TABLE emp
(
	emp_no BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(60),
	sex VARCHAR(2),
	age INT(3),
	sal DECIMAL(17),
	db_source VARCHAR(60)
);

INSERT INTO emp(NAME,sex,age,sal,db_source) VALUES('张三疯','M',99,9999,DATABASE());
INSERT INTO emp(NAME,sex,age,sal,db_source) VALUES('李四疯','F',18,2800,DATABASE());
INSERT INTO emp(NAME,sex,age,sal,db_source) VALUES('王五疯','M',23,3500,DATABASE());
INSERT INTO emp(NAME,sex,age,sal,db_source) VALUES('赵六疯','M',30,6500,DATABASE());

5.6 DAO编码

  1. 新建DAO
@Mapper
public interface EmpDao {
   public List<Emp> getAll();
   public boolean addEmp(Emp emp);
   public Emp getEmpById(Integer id);
   public boolean delEmp(Integer id);
}
  1. 新建EmpMapper.xml,文件路径需和yml的配置保持一致

 
<mapper namespace="com.emall.dao.EmpDao"> 
	<select id="getAll" resultType="Emp">
		SELECT 
			emp_no empNo,
			NAME,
			sex,
			age,
			sal,
			db_source dbSource
		FROM emp
	select>
	
	<insert id="addEmp" parameterType="Emp">
		INSERT INTO emp(name,sex,age,sal,db_source) 
		VALUES(#{name},#{sex},#{age},#{dbSource},DATABASE());
	insert>
	
	<select id="getEmpById" resultType="Emp" parameterType="Integer">
		SELECT 
			emp_no empNo,
			NAME,
			sex,
			age,
			sal,
			db_source dbSource
		FROM emp
		WHERE emp_no = #{empNo}
	select>
	
	<delete id="delEmp" parameterType="Integer">
		DELETE FROM emp
		WHERE emp_no = #{empNo}
	delete>
mapper>

5.7 Service编码

public interface EmpService {
	public List<Emp> getAll();
	public boolean addEmp(Emp emp);
	public Emp getEmpById(Integer id);
	public boolean delEmp(Integer id);
}
@Service
public class EmpServiceImpl implements EmpService{
	
	@Autowired
	private EmpDao dao;

	@Override
	public List<Emp> getAll() {
		return dao.getAll();
	}

	@Override
	public boolean addEmp(Emp emp) {
		return dao.addEmp(emp);
	}

	@Override
	public Emp getEmpById(Integer id) {
		return dao.getEmpById(id);
	}

	@Override
	public boolean delEmp(Integer id) {
		return dao.delEmp(id);
	}
}

5.8 Controller编码

@RestController
public class EmpController {

	@Autowired
	private EmpService service;
	
	@PostMapping("/emp/add")
	public boolean add(@RequestBody Emp emp){
		return service.addEmp(emp);
	}
	
	@GetMapping("/emp/get/{id}")
	public Emp get(@PathVariable Integer id){
		return service.getEmpById(id);
	}
	
	@GetMapping("/emp/get/list")
	public List<Emp> list(){
		return service.getAll();
	}
	
	@DeleteMapping("/emp/delete/{id}")
	public boolean delete(@PathVariable Integer id){
		return service.delEmp(id);
	}
}

5.9 启动类

注意:该类必须放在所有类的上级包中

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

运行启动类程序并测试。

6. 员工模块服务消费者构建

6.1 New Maven Module

SpringCloud入门 - 业务模块搭建(二)_第6张图片
SpringCloud入门 - 业务模块搭建(二)_第7张图片

6.2 pom配置

<dependencies>
    
    <dependency>
        <groupId>com.kgcgroupId>
        <artifactId>emall-apiartifactId>
        <version>0.0.1-SNAPSHOTversion>
    dependency>
    
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
        
        <exclusions>  
            <exclusion>  
                <groupId>org.springframework.bootgroupId>  
                <artifactId>spring-boot-starter-tomcatartifactId>  
            exclusion>  
        exclusions>  
    dependency>
dependencies>

6.3 application.yml配置

server:
  port: 80

80端口如果被System进程占用,可以修改注册表解决,参考下图
SpringCloud入门 - 业务模块搭建(二)_第8张图片

6.4 配置RestTemplate

暂时的目的是配置一个RestTemplate Bean,利用该对象远程调用服务提供者

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

6.5 Controller编码

@RestController
public class EmpController {

	@Autowired
	//RestTemplate是一种简单的访问restful服务模板类
	private RestTemplate rt;
	
	private static final String URL_PREFIX = "http://localhost:8001";//远程服务
	
	@RequestMapping(value="/consumer/emp/add")
	public boolean add(Emp emp){
		return rt.postForObject(URL_PREFIX + "/emp/add", emp, Boolean.class);
	}
	@RequestMapping(value="/consumer/emp/get/{id}")
	public Emp get(@PathVariable("id") Integer id){
		return rt.getForObject(URL_PREFIX + "/emp/get/" + id, Emp.class);
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/consumer/emp/get/list")
	public List<Emp> list(){
		return rt.getForObject(URL_PREFIX + "/emp/get/list" , List.class); 
	}
	@RequestMapping(value="/consumer/emp/delete/{id}")
	public void delete(@PathVariable("id") Integer id){
		rt.delete(URL_PREFIX + "/emp/delete/" + id, Boolean.class);
	}
}

6.6 启动类

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

6.7 测试

分别启动员工服务提供者和员工服务消费者两个服务,然后在浏览器中发请求,
测试成功则基础模块搭建成功!!!

你可能感兴趣的:(Spring,Cloud)