笔者一直有个观念,学习一个东西最好的方式是结合一个实际案例一起学习。
在本篇中,我们将开发一个简单的SIM(学生信息管理)的项目,作为我们学习springCloud的一个案例,后面的文章笔者也会基于这个案例进行更深入的开发和探讨。
好了,废话不多讲,我们先搭建这个项目。(项目基于maven构建)
sim-parent 父工程(pom工程),提供所有子项目的顶级配置。
sim-base 基础工程,含有 model、基础util等
sim-provider 服务提供者工程
sim-consumer 服务消费者工程
数据库:db_sim,数据库中现只有一张学生表 t_student
CREATE TABLE `t_student` (
`studentId` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(50) DEFAULT NULL COMMENT '姓名',
`birthday` varchar(24) DEFAULT NULL COMMENT '生日yyyy-MM-dd',
`phone` varchar(24) DEFAULT NULL COMMENT '手机号',
`address` varchar(200) DEFAULT NULL COMMENT '家庭地址',
`createtime` varchar(24) DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`studentId`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
插入一些初始数据
INSERT INTO `t_student`(NAME ,birthday,phone,address,createtime)
VALUE('张三','1991-09-23','1357788888','北京',NOW());
INSERT INTO `t_student`(NAME ,birthday,phone,address,createtime)
VALUE('李四','1991-09-20','1357788888','广州',NOW());
INSERT INTO `t_student`(NAME ,birthday,phone,address,createtime)
VALUE('王五','1991-09-24','1357788888','杭州',NOW());
注 : 现在这个项目暂时未使用到springcloud的任何东西(使用到了springboot),后面我们讲一步步地进行 spring cloud化 。
pom.xml
<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.tingcream.sim</groupId> <artifactId>sim-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <!-- 定义依赖管理 --> <dependencyManagement> <dependencies> <!-- junit版本 4.12 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 定义springboot版本1.5.13 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.5.13.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!-- spring-boot log4j支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency> <!-- 阿里巴巴 fastjson 1.2.29 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.29</version> </dependency> <!-- apache lang 基本数据类型 、集合、数组工具集 jar包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <!-- mybatis 依赖jar包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- mybatics 与spring 整合插件包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!-- 阿里巴巴数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.31</version> </dependency> </dependencies> </dependencyManagement> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> <include>**/*.yml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> <include>**/*.yml</include> </includes> </resource> </resources> <plugins> <!-- mvn test 乱码问题解决 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <configuration> <forkMode>once</forkMode> <argLine>-Dfile.encoding=UTF-8</argLine> </configuration> </plugin> <!-- maven 编译 插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${maven.compiler.source}</source> <!--JDK 1.7 --> <target>${maven.compiler.target}</target> <!--JDK 1.7 --> <encoding>${project.build.sourceEncoding}</encoding> <!-- UTF-8 --> </configuration> </plugin> <!-- maven 资源 插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <configuration> <encoding>utf-8</encoding> </configuration> </plugin> <!-- 打源码包的插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>attach-sources</id> <phase>install</phase><!-- 要绑定到的生命周期的阶段 在verify之后,install之前执行下面指定的goal --> <goals> <goal>jar-no-fork</goal><!-- 类似执行mvn sources:jar --> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <modules> <module>../sim-base</module> <module>../sim-provider</module> <module>../sim-consumer</module> </modules> </project>
pom.xml
<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> <artifactId>sim-base</artifactId> <packaging>jar</packaging> <name>sim-base</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <parent> <groupId>com.tingcream.sim</groupId> <artifactId>sim-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../sim/pom.xml</relativePath> </parent> </project>
Student.java
package com.tingcream.simBase.model; import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = 1L; private Integer studentId; private String name; private String birthday; private String phone; private String address; private String createtime; public Integer getStudentId() { return studentId; } public void setStudentId(Integer studentId) { this.studentId = studentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } }TLDateFormatUtil.java
package com.tingcream.simBase.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 日期--时间转换工具类 * 线程安全 * @author jelly * */ public class TLDateFormatUtil { private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static Date parse(String dateStr) throws ParseException { return threadLocal.get().parse(dateStr); } public static String format(Date date) { return threadLocal.get().format(date); } }
学生 controller 、service 、mapper 、springboot入口类。
StudentProviderController.java
package com.tingcream.simProvider.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tingcream.simBase.model.Student; import com.tingcream.simProvider.service.StudentProviderService; @RestController @RequestMapping("/student") public class StudentProviderController { @Autowired private StudentProviderService studentProviderService; /** * 查询列表 list * @return */ @GetMapping("/list") public List<Student> list(){ return studentProviderService.findAll(); } /** * 根据id查询 一个学生 * @param id * @return */ @GetMapping("/get/{id}") public Student get(@PathVariable("id") Integer id ){ return studentProviderService.findById(id); } /** * 保存一个学生 成功返回true,失败返回false * @param student * @return */ @PostMapping("/save") public boolean save(@RequestBody Student student){ try { studentProviderService.save(student); return true ; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 更新一个学生 成功返回true,失败返回false * @param student * @return */ @PostMapping("/update") public boolean update(@RequestBody Student student){ try { int count =studentProviderService.update(student); if(count>0){ return true; }else{ return false; } } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据id删除 一个学生 * @param id * @return */ @GetMapping("/delete/{id}") public boolean delete(@PathVariable("id") Integer id ){ try { int count =studentProviderService.deleteById(id); if(count>0){ return true ; }else{ return false; } } catch (Exception e) { e.printStackTrace(); return false; } } }StudentProviderService.java
package com.tingcream.simProvider.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.tingcream.simBase.model.Student; import com.tingcream.simBase.util.TLDateFormatUtil; import com.tingcream.simProvider.mapper.StudentMapper; @Service("studentProviderService") public class StudentProviderService { @Autowired private StudentMapper studentMapper; public List<Student> findAll() { return studentMapper.findAll(); } public Student findById(Integer id) { return studentMapper.findById(id); } @Transactional public int save(Student student){ student.setCreatetime(TLDateFormatUtil.format(new Date())); return studentMapper.save(student); } @Transactional public int update(Student student){ return studentMapper.update(student); } @Transactional public int deleteById(int id){ return studentMapper.deleteById(id); } }
StudentMapper.java 、 StudentMapper.xml
package com.tingcream.simProvider.mapper; import java.util.List; import com.tingcream.simBase.model.Student; public interface StudentMapper { public List<Student> findAll(); public int save(Student student); public int update(Student student); public int deleteById(int id); public Student findById(int id); }
<?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.tingcream.simProvider.mapper.StudentMapper" > <insert id="save" parameterType="Student"> INSERT INTO t_student(`studentId`,`name`,`birthday`,`phone`,`address`,`createtime`) VALUES(#{studentId},#{name},#{birthday},#{phone},#{address},#{createtime}) </insert> <select id="findAll" resultType="Student"> SELECT * FROM t_student order by createtime desc </select> <update id="update" parameterType="Student"> update t_student t <set> <if test="name!=null and name!='' " > t.name=#{name}, </if> <if test="birthday!=null and birthday!='' " > t.birthday=#{birthday}, </if> <if test="phone!=null and phone!='' " > t.phone=#{phone}, </if> <if test="address!=null and address!='' " > t.address=#{address}, </if> <if test="createtime!=null and createtime!='' " > t.createtime=#{createtime}, </if> </set> where t.studentId=#{studentId} </update> <select id="findById" parameterType="int" resultType="Student"> SELECT * FROM `t_student` t WHERE t.`studentId`=#{_parameter} </select> <delete id="deleteById" parameterType="int"> DELETE FROM t_student WHERE studentId=#{_parameter} </delete> </mapper>
springboot入口类 SimProviderApp.java
package com.tingcream.simProvider; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; @SpringBootConfiguration @EnableAutoConfiguration(exclude={ //排除自动配置 DataSourceAutoConfiguration.class,//数据库 数据源 DataSourceTransactionManagerAutoConfiguration.class,//数据库事务 JdbcTemplateAutoConfiguration.class,//jdbcTemplate AopAutoConfiguration.class }) @ComponentScan @ImportResource({"classpath:/spring.xml"}) @PropertySource("classpath:/jdbc.properties") public class SimProviderApp extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure( SpringApplicationBuilder builder) { return builder.sources(SimProviderApp.class); } public static void main(String[] args) { SpringApplication.run(SimProviderApp.class, args); } }
application.yml
#服务器基本配置 server: port: 7001 context-path: / #devtool 热加载工具 spring: devtools: restart: enabled: true exclude: resources/**
jdbc.properties
#驱动全类名 jdbc.driverClassName = com.mysql.jdbc.Driver #本机环境 jdbc.url =jdbc:mysql://localhost:3306/db_sim?useUnicode=true&characterEncoding=UTF8&useSSL=false jdbc.username = root jdbc.password = 123456 #初始化连接数 druid.initialSize = 3 #最大活跃连接数 druid.maxActive = 10 #最小空闲连接数 druid.minIdle = 2 #最大连接等待时间 毫秒 druid.maxWait = 60000 #超过时间限制是否回收 druid.removeAbandoned = true #超时丢弃连接 1800秒 即30分钟 druid.removeAbandonedTimeout = 1800 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 druid.timeBetweenEvictionRunsMillis = 60000 #配置一个连接在池中最小生存的时间,单位是毫秒 druid.minEvictableIdleTimeMillis = 300000 #用来检测连接是否有效的sql,要求是一个查询语句 druid.validationQuery = SELECT 1 FROM DUAL #申请连接的时候检测 druid.testWhileIdle =true #申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 druid.testOnBorrow = false #归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 druid.testOnReturn = false #打开PSCache,并且指定每个连接上PSCache的大小 druid.poolPreparedStatements = true druid.maxPoolPreparedStatementPerConnectionSize = 20 # 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计stat 日志用的log4j 防御SQL注入的wall druid.filters =stat,config
log4j.properties
log4j.rootLogger=info,stdout,D #控制台日志 debug 级别 log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.Threshold = debug log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n #文件日志 debug级别 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = e:/log/sim-provider/sim-provider.log log4j.appender.D.Append = true log4j.appender.D.Threshold = debug log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
spring.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd"> <!-- aspectj 切面的支持 和注解支持--> <aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true"/> <context:annotation-config /> <!--阿里巴巴数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接数量 --> <property name="initialSize" value="${druid.initialSize}"/> <!--最大并发连接数 --> <property name="maxActive" value="${druid.maxActive}" /> <!-- 最小空闲连接数 --> <property name="minIdle" value="${druid.minIdle}"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${druid.maxWait}"/> <!-- 超过时间限制是否回收 --> <property name="removeAbandoned" value="${druid.removeAbandoned}"/> <!-- 超过时间限制多长; --> <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}"/> <!-- 用来检测连接是否有效的sql,要求是一个查询语句 --> <property name="validationQuery" value="${druid.validationQuery}"/> <!-- 申请连接的时候检测 --> <property name="testWhileIdle" value="${druid.testWhileIdle}" /> <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnBorrow" value="${druid.testOnBorrow}"/> <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnReturn" value="${druid.testOnReturn}"/> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}"/> <!-- 属性类型是字符串,通过别名的方式配置扩展插件, 常用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防御SQL注入的filter:wall --> <property name="filters" value="${druid.filters}"/> </bean> <!--5 mybatics sqlSessionFactory 工厂配置 --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--引入数据源dataSource --> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:SqlMapConfig.xml" /> </bean> <!-- 6 自动扫描mapper sql映射文件base包 xxxMapper.xml 和xxxMapper.java 的dao接口文件 默认的mapper扫描器 采用SIMPLE模式--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 如basePackage 有多个需要用 逗号隔开 --> <property name="basePackage" value="com.tingcream.simProvider.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property> </bean> <!-- 10 spring jdbc事务 管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--11 使用注解 声明式事务管理 --> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> </beans>
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 启动延迟加载 积极加载false --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <setting name="logImpl" value="LOG4J" /> </settings> <!-- 实体bean 批量别名 --> <typeAliases> <package name="com.tingcream.simBase.model"/> </typeAliases> <mappers> </mappers> </configuration>
pom.xml
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>sim-provider</artifactId> <packaging>war</packaging> <name>sim-provider Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.tingcream.sim</groupId> <artifactId>sim-base</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- spring-boot web支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 排除spring-boot中 默认的logging支持 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- spring-boot log4j支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <!-- <version>1.3.8.RELEASE</version> --> </dependency> <!-- spring-boot test支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- spring boot devtools 开发者工具 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- tomcat支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- 阿里巴巴 fastJson 解析器 jar包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <!-- <version>1.2.29</version> --> </dependency> <!-- spring aop 切面jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <!-- spring 切面 织入jar包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <!-- mybatics 与spring 整合插件包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <!-- <version>1.2.3</version> --> </dependency> <!-- mybatis 依赖jar包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <!-- <version>3.3.0</version> --> </dependency> <!--jdbc mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--5.1.46 --> </dependency> <!-- spring jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <!-- 4.3.18 --> </dependency> <!-- 阿里巴巴数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <!-- <version>1.0.31</version> --> <exclusions> <exclusion> <artifactId>jconsole</artifactId> <groupId>com.alibaba</groupId> </exclusion> <exclusion> <artifactId>tools</artifactId> <groupId>com.alibaba</groupId> </exclusion> </exclusions> </dependency> <!-- apache lang 基本数据类型 、集合、数组工具集 jar包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <!-- <version>3.3.2</version> --> </dependency> </dependencies> <build> <finalName>sim-provider</finalName> </build> <parent> <groupId>com.tingcream.sim</groupId> <artifactId>sim-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../sim/pom.xml</relativePath> </parent> </project>
学生controller ,springboot入口类 ,等。
StudentConsumerController.java
package com.tingcream.simConsumer.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.tingcream.simBase.model.Student; @RestController @RequestMapping("/student") public class StudentConsumerController { @Autowired private RestTemplate restTemplate; private String PRE_URL="http://localhost:7001/"; /** * 学生列表 list * @return */ @SuppressWarnings("unchecked") @GetMapping("/list") public List<Student> list(){ return restTemplate.getForObject(PRE_URL+"/student/list", List.class); } /** * 根据id查询一个学生 * @return */ @GetMapping(value="/get/{id}") public Student get(@PathVariable("id") Integer id){ return restTemplate.getForObject(PRE_URL+"/student/get/"+id, Student.class); } /** * 根据id删除一个学生 * @return */ @GetMapping(value="/delete/{id}") public boolean delete(@PathVariable("id") Integer id){ return restTemplate.getForObject(PRE_URL+"/student/delete/"+id, Boolean.class); } /** * 添加学生 * @param student * @return */ @PostMapping(value="/save") public boolean save(Student student){ return restTemplate.postForObject(PRE_URL+"/student/save", student, Boolean.class); } /** * 修改学生 * @param student * @return */ @PostMapping(value="/update") public boolean update(Student student){ return restTemplate.postForObject(PRE_URL+"/student/update", student, Boolean.class); } }
MyConfiguration.java
package com.tingcream.simConsumer.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class MyConfiguration { /** * 定义调用rest服务模版对象 */ @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
SimConsumerApp.java
package com.tingcream.simConsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan public class SimConsumerApp extends SpringBootServletInitializer{ //实现SpringBootServletInitializer接口 ,需实现此方法。 可以war包形式 发布到tomcat中 @Override protected SpringApplicationBuilder configure( SpringApplicationBuilder builder) { return builder.sources(SimConsumerApp.class); } public static void main(String[] args) { SpringApplication.run(SimConsumerApp.class, args); } }
application.yml
#服务器基本配置 server: port: 80 context-path: / #devtool 热加载工具 spring: devtools: restart: enabled: true exclude: resources/**
log4j.properties
log4j.rootLogger=info,stdout,D #控制台日志 debug 级别 log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.Threshold = debug log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n #文件日志 debug级别 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = e:/log/sim-consumer/sim-consumer.log log4j.appender.D.Append = true log4j.appender.D.Threshold = debug log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
pom.xml
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>sim-consumer</artifactId> <packaging>war</packaging> <name>sim-consumer Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.tingcream.sim</groupId> <artifactId>sim-base</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- spring-boot web支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 排除spring-boot中 默认的logging支持 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- spring-boot log4j支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <!-- <version>1.3.8.RELEASE</version> --> </dependency> <!-- spring-boot test支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- spring boot devtools 开发者工具 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <finalName>sim-consumer</finalName> </build> <parent> <groupId>com.tingcream.sim</groupId> <artifactId>sim-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../sim/pom.xml</relativePath> </parent> </project>
ok,一个简单的RESTFull 风格的学生信息管理项目就搭建完成了 。
依次启动服务提供者 SimProviderApp 和服务消费者SimConsumerApp ,浏览器访问 http://localhost:7001/student/list http://localhost/student/list 查询学生列表。
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1