火车抢票系统的实现(一)搭建项目框架

springboot quick start

https://projects.spring.io/spring-boot/
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/

1.修改pom,添加依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2.建立目录结构,controller,service,dao

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.创建MainApplication DemoController

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

4.创建Result

result用于存放调用的结果

包含返回的状态码Code,信息msg和数据data

package com.pro.miaosha.result;

public class Result<T> {
	
	private int code;
	private String msg;
	private T data;
	
	/**
	 *  成功时候的调用
	 * */
	public static  <T> Result<T> success(T data){
		return new Result<T>(data);
	}
	
	/**
	 *  失败时候的调用
	 * */
	public static  <T> Result<T> error(CodeMsg codeMsg){
		return new Result<T>(codeMsg);
	}
	
	private Result(T data) {
		this.data = data;
	}
	
	private Result(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}
	
	private Result(CodeMsg codeMsg) {
		if(codeMsg != null) {
			this.code = codeMsg.getCode();
			this.msg = codeMsg.getMsg();
		}
	}
	//这里还有setter和getter,篇幅限制先省略
}

5.创建CodeMsg

用于存放状态码和提示信息

package com.pro.miaosha.result;

public class CodeMsg {
	
	private int code;
	private String msg;
	
	//通用的错误码
	public static CodeMsg SUCCESS = new CodeMsg(0, "success");
	public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常");
	public static CodeMsg BIND_ERROR = new CodeMsg(500101, "参数校验异常:%s");
	//登录模块 5002XX
	public static CodeMsg SESSION_ERROR = new CodeMsg(500210, "Session不存在或者已经失效");
	public static CodeMsg PASSWORD_EMPTY = new CodeMsg(500211, "登录密码不能为空");
	public static CodeMsg MOBILE_EMPTY = new CodeMsg(500212, "手机号不能为空");
	public static CodeMsg MOBILE_ERROR = new CodeMsg(500213, "手机号格式错误");
	public static CodeMsg MOBILE_NOT_EXIST = new CodeMsg(500214, "手机号不存在");
	public static CodeMsg PASSWORD_ERROR = new CodeMsg(500215, "密码错误");
	
	//商品模块 5003XX
	
	//订单模块 5004XX
	
	//秒杀模块 5005XX
	
	private CodeMsg( ) {
	}
			
	private CodeMsg( int code,String msg ) {
		this.code = code;
		this.msg = msg;
	}
	
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public CodeMsg fillArgs(Object... args) {
		int code = this.code;
		String message = String.format(this.msg, args);
		return new CodeMsg(code, message);
	}

	@Override
	public String toString() {
		return "CodeMsg [code=" + code + ", msg=" + msg + "]";
	}	
}

浏览访问http://localhost:8080/demo/hello/api

6.集成thymeleaf

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

7.添加配置application.properties

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

注意后面不能与空格 否则会找不到模板

8.与前端交接template/hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'hello:'+${name}" ></p>
</body>
</html>

9.集成mybatis

大纲:

  • 添加依赖
  • application.properties配置druid
  • 数据库中建立表 name+id
  • 在domain中添加一个叫User的对象(包含name和id)
  • 在dao中添加一个接口叫UserDao(@Mapper.@Select @Insert)
  • userService 中有一个@autowired的userdao,在getById当中直接调用UserDao的getById

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
添加依赖:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.1</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.5</version>
</dependency>

添加数据源配置druid

#mybatis
mybatis.type-aliases-package=com.imooc.miaosha.domain
mybatis.mapperLocations = classpath:com/imooc/miaosha/dao/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
#datasource
spring.datasource.url=jdbc:mysql://10.110.3.62:3333/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive=2
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20

添加config:

public class DruidConfig {
	private String url;
	private String username;
	private String password;
	private String driverClassName;
	private String type;
	private String filters;
	private int maxActive;
	private int initialSize;
	private int minIdle;
	private long maxWait;
	private long timeBetweenEvictionRunsMillis;
	private long minEvictableIdleTimeMillis;
	private String validationQuery;
	private boolean testWhileIdle;
	private boolean testOnBorrow;
	private boolean testOnReturn;
	private boolean poolPreparedStatements;
	private int maxOpenPreparedStatements;
  @Bean
	public DataSource druidDataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(url);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
    try {
        datasource.setFilters(filters);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return datasource;
	}
}
	@Bean
	public ServletRegistrationBean druidStatServlet() {
		ServletRegistrationBean reg = new ServletRegistrationBean();
		reg.setServlet(new StatViewServlet());
		reg.addUrlMappings("/druid/*");
		reg.addInitParameter("loginUsername", "caAdmin");
		reg.addInitParameter("loginPassword", "caPass123");
		reg.addInitParameter("logSlowSql", "true");
		reg.addInitParameter("slowSqlMillis", "1000");
		return reg;
	}
  • 添加mysql-connctor、druid依赖

  • 创建数据表User,Service、Dao、Domain

    CREATE TABLE user (
      id int(11) NOT NULL,
      name varchar(24) DEFAULT NULL,
      PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    
  • @Select注解

    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.imooc.miaosha.dao.UserDao">
    </mapper>
    

(1)getById测试
(2)事务 @Transactional 测试

10.整合redis

  • 安装redis
    下载redis安装文件 http://redis.io/redis-4.0.2.tar.gz

    tar -zvxf redis-4.0.2.tar.gz
    cd redis-4.0.2
    make 
    make install
    src/redis-server & //启动服务器
    src/redis-cli //客户端连接
    util/install_server.sh 安装成系统服务
    chkconfig –-list | grep redis 查看是否开机启动
    
  • 配置redis.conf

    daemonize yes
    bind 0.0.0.0
    requirepass
    

添加配置

引入jedis和fastjson依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.38</version>
</dependency>

添加配置:

#redis
redis.host=10.110.3.62
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3
@ConfigurationProperties(prefix="redis")
@Component
public class RedisConfig {
	private String host;
	private int port;
	private int timeout;//秒
	private String password;
	private int poolMaxTotal;
	private int poolMaxIdle;
	private int poolMaxWait;//秒
}

编写RedisSerive KeyPrefix BaseKey

package com.pro.miaosha.redis;

public interface KeyPrefix {
	public int expireSeconds();
	public String getPrefix();
}

package com.pro.miaosha.redis;

public abstract class BasePrefix implements KeyPrefix{

	private int expireSeconds;
	private String prefix;
	
	public BasePrefix(String prefix) {
		this(0,prefix);
	}
	
	public BasePrefix(int expireSeconds, String prefix) {
		super();
		this.expireSeconds = expireSeconds;
		this.prefix = prefix;
	}
	public int expireSeconds() {
		return expireSeconds;//默认0代表永不过期
	}

	public String getPrefix() {
		String className = getClass().getSimpleName();
		return className+":"+prefix;	
	}
}
package com.pro.miaosha.redis;

public class UserKey extends BasePrefix{
	
	private UserKey(String prefix) {
		super(prefix);
	}
	
	private UserKey(int expireSeconds,String prefix) {
		super(expireSeconds,prefix);
	}
	
	public static UserKey getById = new UserKey("id");
	public static UserKey getByName = new UserKey("name");
	
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值