秒杀系统(一)----环境搭建及集成Mybatis、Redis
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的更多相关文章
- QT5.6.0 VS2013 Win764位系统QT环境搭建过程
QT5.6.0 VS2013 Win764位系统QT环境搭建过程 没用过QT自己跟同事要了安装包,按照同事指导方法操作安装部署开发环境结果遇到好多问题,错误网上搜遍了所有帖子也没有找到合适的解决方案. ...
- Java高并发秒杀系统API之SSM框架集成swagger与AdminLTE
初衷与整理描述 Java高并发秒杀系统API是来源于网上教程的一个Java项目,也是我接触Java的第一个项目.本来是一枚c#码农,公司计划部分业务转java,于是我利用业务时间自学Java才有了本文 ...
- idea 搭建 SpringBoot 集成 mybatis
编译器:IDEA2018.2.3 环境:win10,jdk1.8,maven3.4 数据库:mysql 5.7 备注:截图较大,如果看不清,可以在图片上右键=>在新标签页中打开 查看高清大图 ...
- Linux系统zookeeper环境搭建(单机、伪分布式、分布式)
本人现在对zookeeper的环境搭建做一个总结,一般zookeeper的安装部署可以有三种模式,单机模式.伪分布式和分布式,这三种模式在什么时候应用具体看大家的使用场景,如果你只有一台机器且只是想自 ...
- 基于CentOS-6.9_x64系统QT环境搭建
想从事QT开发的人员,首先要做的第一件事就是开发环境的搭建.本人也是一位刚入门的新手,为了搭建这么一个环境,参考了很多的网上教程,然而中间依然走了不少弯路.现将过程记录下来. 一.开发环境 Ce ...
- Weex的环境搭建以及集成到Android项目
最近由于公司的需要,初步研究了Weex,Weex是阿里开发的一个web的框架,官方的介绍如下: Weex 是一套简单易用的跨平台开发方案,能以 web 的开发体验构建高性能.可扩展的 native 应 ...
- Appium (win7系统)环境搭建----完整版
首先感谢 http://www.cnblogs.com/puresoul/p/4696638.html 和 http://www.cnblogs.com/fnng/p/4540731.html ...
- appium在windows系统下环境搭建
对于appium的介绍我就不说了,之前的文章介绍过.下面直入主题. 命令版本在安装过程中需要有python2环境,装完你可以装python3来写脚本. 环境要求: JDK >java语言安装包 ...
- ELK日志分析平台系统CentOS7环境搭建和基本使用
一.搭建环境 系统环境:CentOS7 安装iptables:https://blog.csdn.net/momo_mutou/article/details/81739155 jdk1.8: ht ...
随机推荐
- 最小化安装CentOS 7 系统
目录 CentOS 程序准备 开始安装系统 创建虚拟机 安装系统 CentOS 运维最常接触的系统就是CentOS系统,无论是版本 6 还是版本 7 而且在安装系统时,讲究最小化安装系统,之后当需要什 ...
- react简单的tab切换 (styled-components)
其实,在我们日常的编程当中,经常会碰到tab切换的模块,那么,实现他的方法也有很多中,下面是一款简单,容易理解的react tab切换方法. 通过设置state中的current 属性去控制tab 和 ...
- 【重学Node.js 第3篇】mongodb以及mongoose的使用
mongodb以及mongoose的使用 本篇为这个系列的第三篇,想看更多可以直接去github的项目:https://github.com/hellozhangran/happy-egg-serve ...
- React-native ESLint & Prettier & Pre-commit Hook配置
目录 前言 一 eslint 1.1. 局部安装eslint 1.2 初始化配置文件 1.3 安装步骤 1.3.1 ESLint 风格 选Use a popular style guide 1.3.2 ...
- [TimLinux] Python 迭代器(iterator)和生成器(generator)
1. 可迭代对象 from collection import Iterable class Iterable(metaclass=ABCMeta): ... def __iter__(self): ...
- [TimLinux] JavaScript 给表单提前之前进行验证的方法
1. onSubmit事件 这个事件是注册到form表单上的,不是注册在input type="submit"这个input按钮上面的. 2. 注册方式 HTML内部注册:< ...
- Codeforces Round #605 (Div. 3) E - Nearest Opposite Parity
题目链接:http://codeforces.com/contest/1272/problem/E 题意:给定n,给定n个数a[i],对每个数输出d[i]. 对于每个i,可以移动到i+a[i]和i-a ...
- POJ 3041 Asteroids(二分图模板题)
Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N g ...
- 拓展KMP分析
拓展kmp是对KMP算法的扩展,它解决如下问题: 定义母串S,和字串T,设S的长度为n,T的长度为m,求T与S的每一个后缀的最长公共前缀,也就是说,设extend数组,extend[i]表示T与S[i ...
- UESTC-1975弗吉桑(回文串,manacher算法)
弗吉桑 Time Limit: 3000 MS Memory Limit: 64 MB Submit Status 弗吉桑是一座横跨清水河大草原的活火山,位于子科技大学主楼东北方约 80km ...