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. 09-kubernetes configMap secret

    目录 配置容器化应用配置的方式 命令创建和测试configMap 创建一个Pod 挂在测试 命令行文件类创建方式 创建Pod测试 创建后测试 贴近实际进行测试 创建后测试 secret 举例测试 ge ...

  2. AWK工具 使用介绍

    第6周第5次课(4月27日) 课程内容: 9.6/9.7 awk扩展把这里面的所有练习题做一下http://www.apelearn.com/study_v2/chapter14.html 9.6/9 ...

  3. 对python的初步了解

    一,Python简介 Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具 ...

  4. ThreadLocal 源码解读

    一.引入 public class Thread implements Runnable { /* 前面略 */ /* ThreadLocal values pertaining to this th ...

  5. TypeScript躬行记(1)——数据类型

    TypeScript不仅支持JavaScript所包含的数据类型,还额外扩展了许多实用的数据类型,例如枚举.空值.任意值等. 一.JavaScript的数据类型 JavaScript的数据类型包括6种 ...

  6. Eclipse for Tricore 的安装方法

    1.安装JDK32位版 2.安装Eclipse for Tricore 32位版(应该也只有32位的) 3.OK(如果打开Tricore提示找不到JDK的话,在网上搜索如何配置JDK,修改环境变量) ...

  7. UIContainerView纯代码实现及原理介绍

    UIContainerView纯代码实现及原理介绍 1.1-在StoryBoard中使用UIContainerView 1.2-纯代码使用UIContainerView 1.3-UIContainer ...

  8. CodeForces1006D-Two Strings Swaps

    D. Two Strings Swaps time limit per test 2 seconds memory limit per test 256 megabytes input standar ...

  9. linux mysql,tomcat与java的安装

    先将服务器的安全组设置为 把所有端口或者所需要的端口开放 然后测试远程访问 ssh 用户@ip                       登录 输入密码 service iptables stop  ...

  10. A.Sweet Problem

    题目:甜蜜的问题 题意:你有三堆糖果:红色,绿色,蓝色 第一堆有r个糖果,第二堆有g个糖果,第三堆有b个糖果 每天都可以吃两个不同颜色的糖果,找出可以吃糖果的最大天数 分析:先排下序,如果最大堆大于等 ...