秒杀系统(一)----环境搭建及集成Mybatis、Redis
1.1 环境搭建——pom文件
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
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代码
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
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
* @return
*/
public static
return new Result
}
/**
* 失败得时候调用
* @param codeMsg
* @param
* @return
*/
public static
return new Result
}
9. controller层:
@Controller
@RequestMapping("/demo")
public class SampleController {
@Autowired
private UserService userService;
@RequestMapping("/db/get")
@ResponseBody
public Result
User user = userService.getById(1);
return Result.success(user);
}
@RequestMapping("/db/tx")
@ResponseBody
public Result
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
* @return
*/
public
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
* @return
*/
public
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
* @return
*/
public
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
* @return
*/
public
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
* @return
*/
public
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正得Key;
String realKey = prefix.getPrefix() + key;
return jedis.decr(realKey);
}finally {
returnToPool(jedis);
}
}
/**
* 实体类转换成String类型
* @param value
* @param
* @return
*/
private
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
* @return
*/
private
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 user = redisService.get(UserKey.getById,""+1,User.class);
return Result.success(user);
}
@RequestMapping("/redis/set")
@ResponseBody
public Result
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集成完成。

浙公网安备 33010602011771号