高并发秒杀系统方案(集成Mybatis和Redis)
1.集成Mybatis
第一步,添加依赖:
<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>
第二步:配置properties:
# mybatis mybatis.type-aliases-package=com.imooc.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/imooc/miaosha/dao/*.xml # druid spring.datasource.url=jdbc:mysql://192.168.80.130:3306/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false spring.datasource.username=mmall spring.datasource.password=mmall spring.datasource.driver-class-name=com.mysql.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
在这里我们测试了一下事务:
UserService:
@Transactional public boolean tx() { User u1= new User(); u1.setId(2); u1.setName("2222"); userDao.insert(u1); User u2= new User(); u2.setId(1); u2.setName("11111"); userDao.insert(u2); return true; }
UserDao:
@Insert("insert into user(id, name)values(#{id}, #{name})") public int insert(User user);
2.安装redis:
下载Redis:https://redis.io/
redis的配置文件(vim进入的时候,输入/+关键字是从上往下搜索,?+关键字是从下往上搜索。另外n和N分别是向下匹配和向上匹配):
这个表明任何服务器都能访问:
允许后台执行:
然后:
现在我们需要访问之前需要输入密码:
设置:
重启下:
生成redis系统服务:
到这里为止,redis安装完成!
接下来在SpringBoot中集成redis:
FastJson将对象序列化以后是可读的,将java对象转化成json字符串存到redis服务器里面。
引入依赖:
<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=192.168.80.130 redis.port=6379 redis.timeout=3 redis.password=123456 redis.poolMaxTotal=10 redis.poolMaxIdle=10 redis.poolMaxWait=3
代码此处不贴了。