标签:eid boot install test ica dep target alibaba config
<?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>
# 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
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,则环境搭建成功。
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集成成功。
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
标签:eid boot install test ica dep target alibaba config
原文地址:https://www.cnblogs.com/guoguo327/p/12067585.html