1.1 环境搭建——pom文件
<?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.ustc</groupId>
<artifactId>miaosha</artifactId>
<version>1.0-SNAPSHOT</version> <name>miaosha</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <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> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency> <!-- 连接Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency> <!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency> <!-- jedis连接redis需要的jar -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency> <!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency> <!-- springboot中使用注解导入yml或properties文件需要的jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency> <!-- 引入MD5工具类 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency> <!-- JSR303校验 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency> <!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency> </dependencies> <build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
1.2 环境搭建——application.properties文件配置
# thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
2. 测试环境
1. controller层代码:

@Controller
@RequestMapping("/demo")
public class SampleController {
@RequestMapping("/")
public String thymeleaf(Model model){
model.addAttribute("name","xc");
return "hello";
} 2. 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> 3. 测试结果:
启动项目:浏览器端输入:localhost:8080/demo/
返回结果:hello:xc,则环境搭建成功。
3. 集成mybatis
1. application.properties配置:
# mybatis
mybatis.type-aliases-package=com.ustc.miaosha.domain
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=3000
mybatis.mapperLocations = classpath:com/ustc/miaosha/dao/*.xml # 配置druid连接池
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
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 2. mysql中新建User表:
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3. 向user表中插入一条数据
4. 创建实体类并生成get、set方法:
@Setter
@Getter
public class User {
private int id;
private String name;
}
5. dao层接口: @Mapper
public interface UserDao {
@Select("select * from user where id = #{id}")
User getById(@Param("id") int id); @Insert("insert into user(id,name) values(#{id},#{name})")
int insert(User user);
}
6. Service层接口:
public interface IUserService{
User getById(int id);
boolean tx();
} 7. Service实现类: @Service
public class UserServiceImpl implements IUserService { @Autowired
private UserDao userDao;
public User getById(int id){
return userDao.getById(id);
} @Transactional
public boolean tx(){
User u1 = new User();
u1.setId(2);
u1.setName("lisi");
userDao.insert(u1); User u2 = new User();
u2.setId(1);
u2.setName("li11si");
userDao.insert(u2); return true;
}
} 8. 创建返回值类——CodeMsg类: @Setter
@Getter
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 CodeMsg(int code, String msg) {
this.code = code;
this.msg = msg;
}
} 创建Result类:
@Setter
@Getter
public class Result<T> {
private int code;
private String msg;
private T data; private Result(T data) {
this.code = 0;
this.msg = "success";
this.data = data;
} private Result(CodeMsg codeMsg) {
if (codeMsg == null){
return;
}
this.code = codeMsg.getCode();
this.msg = codeMsg.getMsg();
} /**
* 成功得时候调用
* @param data
* @param <T>
* @return
*/
public static <T> Result<T> success(T data){
return new Result<T>(data);
} /**
* 失败得时候调用
* @param codeMsg
* @param <T>
* @return
*/
public static <T> Result<T> error(CodeMsg codeMsg){
return new Result<T>(codeMsg);
} 9. controller层:
@Controller
@RequestMapping("/demo")
public class SampleController { @Autowired
private UserService userService; @RequestMapping("/db/get")
@ResponseBody
public Result<User> dbGet(){
User user = userService.getById(1);
return Result.success(user);
} @RequestMapping("/db/tx")
@ResponseBody
public Result<Boolean> dbTx(){
userService.tx();
return Result.success(true);
}
} 10. 测试:启动项目,输入localhost:8080/demo/db/get 能够查询到数据,输入localhost:8080/demo/db/get插入一条数据,说明myBatis集成成功。
4. 集成Redis
1. application.properties配置:
#redis
redis.host=192.168.124.128
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3 2. 创建配置文件对应的实体类读取配置文件: @Component
@ConfigurationProperties(prefix = "redis")
@Setter
@Getter
public class RedisConfig {
private String host;
private int port;
private int timeout; //秒
private String password;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;//秒
} 3. 创建RedisPool连接工厂 @Service
public class RedisPoolFactory {
@Autowired
RedisConfig redisConfig; @Bean
public JedisPool jedisPoolFactory(){
System.out.println(redisConfig.toString());
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
JedisPool jp = new JedisPool(poolConfig,redisConfig.getHost(),redisConfig.getPort(),redisConfig.getTimeout()*1000,redisConfig.getPassword(),0);
return jp;
}
} 4. 创建RedisService @Service
public class RedisService { @Autowired
JedisPool jedisPool; /**
* 查询key
* @param prefix
* @param key
* @param clazz
* @param <T>
* @return
*/
public <T> T get(KeyPrefix prefix, String key, Class<T> clazz){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正得Key;
String realKey = prefix.getPrefix() + key;
String str = jedis.get(realKey);
T t = stringToBean(str,clazz);
return t;
}finally {
returnToPool(jedis);
}
} /**
* 存入key
* @param prefix
* @param key
* @param value
* @param <T>
* @return
*/
public <T> Boolean set(KeyPrefix prefix ,String key, T value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str =beanToString(value);
if (str == null || str.length() <= 0){
return false;
}
//生成真正得Key;
String realKey = prefix.getPrefix() + key;
int seconds = prefix.expireSeconds();
if (seconds <= 0){
jedis.set(realKey,str);
}else {
jedis.setex(realKey,seconds,str);
}
return true;
}finally {
returnToPool(jedis);
}
} /**
* 判断key是否存在
* @param prefix
* @param key
* @param <T>
* @return
*/
public <T> Boolean exist(KeyPrefix prefix, String key){ Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正得Key;
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
}finally {
returnToPool(jedis);
}
} /**
* key值自增
* @param prefix
* @param key
* @param <T>
* @return
*/
public <T> Long incr(KeyPrefix prefix, String key){ Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正得Key;
String realKey = prefix.getPrefix() + key;
return jedis.incr(realKey);
}finally {
returnToPool(jedis);
}
} /**
* key值自减
* @param prefix
* @param key
* @param <T>
* @return
*/
public <T> Long decr(KeyPrefix prefix, String key){ Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正得Key;
String realKey = prefix.getPrefix() + key;
return jedis.decr(realKey);
}finally {
returnToPool(jedis);
}
} /**
* 实体类转换成String类型
* @param value
* @param <T>
* @return
*/
private <T> String beanToString(T value) {
if (value == null){
return null;
}
Class<?> clazz = value.getClass();
if (clazz == int.class || clazz == Integer.class){
return ""+value;
}else if (clazz == String.class){
return (String) value;
}else if (clazz == Long.class || clazz == long.class){
return ""+value;
}else {
return JSON.toJSONString(value);
}
} /**
* String类型转换成实体类
* @param str
* @param clazz
* @param <T>
* @return
*/
private <T> T stringToBean(String str, Class<T> clazz) {
if (str == null || str.length() <= 0){
return null;
}
if (clazz == int.class || clazz == Integer.class){
return (T)Integer.valueOf(str);
}else if (clazz == String.class){
return (T)str;
}else if (clazz == Long.class || clazz == long.class){
return (T)Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str),clazz);
}
} private void returnToPool(Jedis jedis) {
if (jedis != null){
jedis.close();
}
} } 5. 测试:
创建KeyPreFifx接口 public interface KeyPrefix {
int expireSeconds();
String getPrefix();
} 创建抽象类BasePrefix @Setter
@Getter
public abstract class BasePrefix implements KeyPrefix { private int expireSeconds; //设置过期时间
private String prefix; public BasePrefix(String prefix){ //0代表永不过期
this(0,prefix);
} public BasePrefix(int expireSeconds, String prefix) {
this.expireSeconds = expireSeconds;
this.prefix = prefix;
}
} 创建UserKey继承抽象类BasePrefix public class UserKey extends BasePrefix {
private UserKey(String prefix) {
super(prefix);
} public static UserKey getById = new UserKey("id");
public static UserKey getByName = new UserKey("name");
} Controller层添加方法:
@RequestMapping("/redis/get")
@ResponseBody
public Result<User> redisGet(){
User user = redisService.get(UserKey.getById,""+1,User.class);
return Result.success(user);
} @RequestMapping("/redis/set")
@ResponseBody
public Result<Boolean> redisSet(){
User user = new User(1,"1111111");
Boolean v1 = redisService.set(UserKey.getById,""+1,user);
return Result.success(v1);
} 启动项目:输入localhost:8080/demo/redis/set插入一条数据,在输入localhost:8080/demo/redis/get查询出刚才插入的数据。 至此,Redis集成完成。

秒杀系统(一)----环境搭建及集成Mybatis、Redis的更多相关文章

  1. QT5.6.0 VS2013 Win764位系统QT环境搭建过程

    QT5.6.0 VS2013 Win764位系统QT环境搭建过程 没用过QT自己跟同事要了安装包,按照同事指导方法操作安装部署开发环境结果遇到好多问题,错误网上搜遍了所有帖子也没有找到合适的解决方案. ...

  2. Java高并发秒杀系统API之SSM框架集成swagger与AdminLTE

    初衷与整理描述 Java高并发秒杀系统API是来源于网上教程的一个Java项目,也是我接触Java的第一个项目.本来是一枚c#码农,公司计划部分业务转java,于是我利用业务时间自学Java才有了本文 ...

  3. idea 搭建 SpringBoot 集成 mybatis

    编译器:IDEA2018.2.3 环境:win10,jdk1.8,maven3.4 数据库:mysql 5.7 备注:截图较大,如果看不清,可以在图片上右键=>在新标签页中打开   查看高清大图 ...

  4. Linux系统zookeeper环境搭建(单机、伪分布式、分布式)

    本人现在对zookeeper的环境搭建做一个总结,一般zookeeper的安装部署可以有三种模式,单机模式.伪分布式和分布式,这三种模式在什么时候应用具体看大家的使用场景,如果你只有一台机器且只是想自 ...

  5. 基于CentOS-6.9_x64系统QT环境搭建

    想从事QT开发的人员,首先要做的第一件事就是开发环境的搭建.本人也是一位刚入门的新手,为了搭建这么一个环境,参考了很多的网上教程,然而中间依然走了不少弯路.现将过程记录下来. 一.开发环境    Ce ...

  6. Weex的环境搭建以及集成到Android项目

    最近由于公司的需要,初步研究了Weex,Weex是阿里开发的一个web的框架,官方的介绍如下: Weex 是一套简单易用的跨平台开发方案,能以 web 的开发体验构建高性能.可扩展的 native 应 ...

  7. Appium (win7系统)环境搭建----完整版

    首先感谢  http://www.cnblogs.com/puresoul/p/4696638.html  和 http://www.cnblogs.com/fnng/p/4540731.html   ...

  8. appium在windows系统下环境搭建

    对于appium的介绍我就不说了,之前的文章介绍过.下面直入主题. 命令版本在安装过程中需要有python2环境,装完你可以装python3来写脚本. 环境要求: JDK >java语言安装包 ...

  9. ELK日志分析平台系统CentOS7环境搭建和基本使用

    一.搭建环境 系统环境:CentOS7 安装iptables:https://blog.csdn.net/momo_mutou/article/details/81739155 jdk1.8:  ht ...

随机推荐

  1. Python高级数据结构-Collections模块

    在Python数据类型方法精心整理,不必死记硬背,看看源码一切都有了之中,认识了python基本的数据类型和数据结构,现在认识一个高级的:Collections 这个模块对上面的数据结构做了封装,增加 ...

  2. @PathVariable 处理参数为空的情况

    @RequestMapping(value = "/get/{id}/{userId}", method = RequestMethod.GET) public Result ge ...

  3. PHP和JavaScript中奖概率算法

    这是一个经典的概率算法. 现在有数组:[10, 20, 30, 40] . 假设对应中奖几率:特等奖10%,一等奖20%,二等奖30%,三等奖40%,总共100%. 算法开始时,从数组中选出一个值$v ...

  4. ajax加载引起瀑布流布局堆叠

    jQuery 瀑布流使用ajax加载数据库图片url ,ajax每次请求到的数据不变时,瀑布流效果没问题. 但当请求到的数据变化时,瀑布流图片格式会重叠 或者相隔很远等等的格式问题,这是由于图片加载是 ...

  5. volatile在外设寄存器基地址定义时的作用

    volatile,作用就是告诉编译器不要因优化而省略此指令,必须每次都直接读写其值,这样就能确保每次读或者写寄存器都真正执行到位.——野火

  6. 接口访问报错:The valid characters are defined in RFC 7230 and RFC 3986

    写了个接口,在测试访问的时候,需要传json串,但是后台报错了 The valid characters are defined in RFC 7230 and RFC 3986 当前使用的tomca ...

  7. react-native-linear-gradient颜色渐变

    目录 一 安装 二 使用 2.1 colors 2.2 start / end eg1:斜角渐变 eg2: 从左到右 2.2 locations eg1: 0.4是渐变的起点,0.6是渐变的终点 一 ...

  8. git 使用详解(3)—— 最基本命令 + .gitignore 文件

    Git 基础 本章将介绍几个最基本的,也是最常用的 Git 命令,以后绝大多数时间里用到的也就是这几个命令.读完本章,你就能初始化一个新的代码仓库,做一些适当配置:开始或停止跟踪某些文件:暂存或提交某 ...

  9. 对于在Dao层,一个DML操作一个事务,升级到Service层,一个用户,一个事务

    原先的连接Connection,只能是来一次,新创建一个连接connection.这样如果事务在Dao层已经默认提交,在service层出错时,对于俩张关联会有俩种不同的结果.为了解决这样的问题,我们 ...

  10. 摄像头CMOS和CCD的比较

    转载自网络,在此做一下总结,仅供参考: 1.CCD每曝光一次,在快门关闭后进行像素转移处理,将每一行中每一个像素(pixel)的电荷信号依序传入“缓冲器”中,由底端的线路引导输出至 CCD 旁的放大器 ...