idea springBoot+mybatis+Redis+Mysql(一)
目录结构
新建maven项目
file->newProject
添加项目必要包
修改pom.xml文件
<?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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>SpringBoot</groupId>
<artifactId>SpringBoot</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<gson.version>2.8.0</gson.version>
<net.iharder.base64.version>2.3.9</net.iharder.base64.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<!-- 打war包用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!--Base64-->
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<version>${net.iharder.base64.version}</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0-RC2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.25-incubating</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware.kryo</groupId>
<artifactId>kryo</artifactId>
<version>2.24.0</version>
</dependency>
<dependency>
<groupId>de.ruedigermoeller</groupId>
<artifactId>fst</artifactId>
<version>2.57</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-push</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.aliyun.mns</groupId>
<artifactId>aliyun-sdk-mns</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-ram</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sts</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
<packaging>war</packaging>
<!-- -->
<build>
<!-- 打war包用 -->
<finalName>SpringBoot</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 打war包用,maven打包的时候告诉maven不需要web.xml,否刚会报找不到web.xml错误 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- -->
</plugins>
</build>
</project>
新建application.properties
server.port=8081 #访问端口号
server.context-path=/test #项目访问跟路径
druid.driver=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://0.0.0.0:3306/test #数据库地址
druid.username= #数据库用户名
druid.password= #数据库密码
druid.init-size=1
druid.min-idel=1
druid.max-active=5
druid.login.timeout.seconds=30
druid.query.timeout.seconds=30
druid.mappers=mappers/*/*.xml #mybatis sql文件扫描路径
mybatis.configuration.call-setters-on-nulls=true
mybatis.configuration.map-underscore-to-camel-case=true
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
配置mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/><!-- 全局映射器启用缓存 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="600"/>
<setting name="callSettersOnNulls" value="true"/>
</settings>
<typeAliases>
<typeAlias type="com.Logos.util.PageData" alias="pd"/>
<!-- 分页 -->
<typeAlias type="com.Logos.util.Page" alias="Page"/>
</typeAliases>
<plugins>
<plugin interceptor="com.Logos.plugin.PagePlugin">
<property name="dialect" value="mysql"/>
<property name="pageSqlId" value=".*ListPage.*"/>
</plugin>
</plugins>
</configuration>
配置log文件
log4j.rootLogger=info,ServerDailyRollingFile,stdout
log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=log/test.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p [%c] - %m%n
log4j.appender.ServerDailyRollingFile.Append=true
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d yyyy-MM-dd HH:mm:ss %p [%c] %m%n
配置sql文件
!
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="TestOtherMapper">
<!--表名 -->
<sql id="tableName">
testOther
</sql>
<!-- 字段 -->
<sql id="Field">
id,
name
</sql>
<!-- 字段值 -->
<sql id="FieldValue">
#{id},
#{name}
</sql>
<!--添加-->
<insert id="save" parameterType="pd">
insert into
<include refid="tableName"></include>
(
<include refid="Field"></include>
) values (
<include refid="FieldValue"></include>
)
</insert>
<!-- 修改 -->
<update id="edit" parameterType="pd">
update
<include refid="tableName"></include>
set name = #{name}
where
id = #{id}
</update>
<!-- 删除 -->
<delete id="del" parameterType="pd">
delete from
<include refid="tableName"></include>
where
id = #{id}
</delete>
<!--查询-->
<select id="selectList" resultType="pd">
select <include refid="Field"></include> from
<include refid="tableName"></include>
</select>
<!--分页-->
<select id="testListPage" parameterType="page" resultType="pd">
select
<include refid="Field"></include>
from
<include refid="tableName"></include>
where 1=1
<if test="pd.name != null">
and name = #{pd.name}
</if>
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Logos.mapper.TestMapper">
<select id="selectList" resultType="pd">
select * from test
</select>
</mapper>
配置 Application
package com.Logos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 7:47 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@SpringBootApplication
@RestController
@ServletComponentScan("com.Logos.configuration")
public class Application {
@RequestMapping("/")
public String index() {
return "Hello Spring Boot";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
分页插件
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 10:47 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class })})
public class PagePlugin implements Interceptor {
private static String dialect = ""; //数据库方言
private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配)
public Object intercept(Invocation ivk) throws Throwable {
if(ivk.getTarget() instanceof RoutingStatementHandler){
RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();
BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQL
BoundSql boundSql = delegate.getBoundSql();
Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
if(parameterObject==null){
throw new NullPointerException("parameterObject尚未实例化!");
}else{
Connection connection = (Connection) ivk.getArgs()[0];
String sql = boundSql.getSql();
//String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计
String fhsql = sql;
String countSql = "select count(0) from (" + fhsql+ ") tmp_count"; //记录统计 == oracle 加 as 报错(SQL command not properly ended)
PreparedStatement countStmt = connection.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);
setParameters(countStmt,mappedStatement,countBS,parameterObject);
ResultSet rs = countStmt.executeQuery();
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
countStmt.close();
Page page = null;
if(parameterObject instanceof Page){ //参数就是Page实体
page = (Page) parameterObject;
page.setEntityOrField(true);
page.setTotalResult(count);
}else{ //参数为某个实体,该实体拥有Page属性
Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");
if(pageField!=null){
page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");
if(page==null)
page = new Page();
page.setEntityOrField(false);
page.setTotalResult(count);
ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通过反射,对实体对象设置分页对象
}else{
throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 属性!");
}
}
String pageSql = generatePageSql(sql,page);
ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //将分页sql语句反射回BoundSql.
}
}
}
return ivk.proceed();
}
private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
Configuration configuration = mappedStatement.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
PropertyTokenizer prop = new PropertyTokenizer(propertyName);
if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {
value = boundSql.getAdditionalParameter(prop.getName());
if (value != null) {
value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
}
} else {
value = metaObject == null ? null : metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());
}
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
}
}
}
}
private String generatePageSql(String sql,Page page){
if(page!=null && Tools.notEmpty(dialect)){
StringBuffer pageSql = new StringBuffer();
if("mysql".equals(dialect)){
pageSql.append(sql);
pageSql.append(" limit "+page.getCurrentResult()+","+page.getShowCount());
}
return pageSql.toString();
}else{
return sql;
}
}
public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this);
}
public void setProperties(Properties p) {
dialect = p.getProperty("dialect");
if (Tools.isEmpty(dialect)) {
try {
throw new PropertyException("dialect property is not found!");
} catch (PropertyException e) {
e.printStackTrace();
}
}
pageSqlId = p.getProperty("pageSqlId");
if (Tools.isEmpty(pageSqlId)) {
try {
throw new PropertyException("pageSqlId property is not found!");
} catch (PropertyException e) {
e.printStackTrace();
}
}
}
}
public class Page implements Serializable {
private int showCount; //每页显示记录数
private int totalPage; //总页数
private int totalResult; //总记录数
private int currentPage; //当前页
private int currentResult; //当前记录起始索引
private boolean entityOrField;
private PageData pd = new PageData();
private Object content;
public void setPage(Page servicePage) {
this.setTotalResult(servicePage.getTotalResult());
this.setTotalPage(servicePage.getTotalPage());
this.setCurrentPage(servicePage.getCurrentPage());
this.setCurrentResult(servicePage.getCurrentResult());
this.setShowCount(servicePage.getShowCount());
this.setEntityOrField(servicePage.isEntityOrField());
}
public Page() {
try {
this.showCount = 10;
} catch (Exception e) {
this.showCount = 15;
}
}
public int getTotalPage() {
if (totalResult % showCount == 0)
totalPage = totalResult / showCount;
else
totalPage = totalResult / showCount + 1;
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalResult() {
return totalResult;
}
public void setTotalResult(int totalResult) {
this.totalResult = totalResult;
}
public int getCurrentPage() {
if (currentPage <= 0)
currentPage = 1;
if (currentPage > getTotalPage())
currentPage = getTotalPage();
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getShowCount() {
return showCount;
}
public void setShowCount(int showCount) {
this.showCount = showCount;
}
public int getCurrentResult() {
currentResult = (getCurrentPage() - 1) * getShowCount();
if (currentResult < 0)
currentResult = 0;
return currentResult;
}
public void setCurrentResult(int currentResult) {
this.currentResult = currentResult;
}
public boolean isEntityOrField() {
return entityOrField;
}
public void setEntityOrField(boolean entityOrField) {
this.entityOrField = entityOrField;
}
public PageData getPd() {
return pd;
}
public void setPd(PageData pd) {
this.pd = pd;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
}
/**
* 说明:参数封装Map
* 创建人:
* 修改时间:
*/
public class PageData extends TreeMap implements Map {
private static final long serialVersionUID = 1L;
Map map;
HttpServletRequest request;
public PageData(HttpServletRequest request) {
this.request = request;
Map properties = request.getParameterMap();
Map returnMap = new TreeMap();
Iterator entries = properties.entrySet().iterator();
Entry entry;
String name = "";
while (entries.hasNext()) {
String value = "";
entry = (Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value += values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
value = value.trim();
value = value.replaceAll("<[^>]*>", "");
value = value.replaceAll(EmojiRegexUtil.getFullEmojiRegex(), "?");
returnMap.put(name, value);
}
map = returnMap;
}
public PageData() {
map = new HashMap();
}
public PageData(Map properties) {
Map returnMap = new TreeMap();
Iterator entries = properties.entrySet().iterator();
Entry entry;
String name = "";
while (entries.hasNext()) {
String value = "";
entry = (Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value += values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
value = value.trim();
value = value.replaceAll("<[^>]*>", "");
value = value.replaceAll(EmojiRegexUtil.getFullEmojiRegex(), "?");
returnMap.put(name, value);
}
map = returnMap;
}
@Override
public Object get(Object key) {
Object obj = null;
if (map.get(key) instanceof Object[]) {
Object[] arr = (Object[]) map.get(key);
obj = request == null ? arr : (request.getParameter((String) key) == null ? arr : arr[0]);
} else {
obj = map.get(key);
}
return obj;
}
public String getString(Object key) {
return (String) get(key);
}
public int getInt(Object key) {
Object o = get(key);
int v;
try {
v = (int) o;
} catch (Exception e1) {
try {
v = (Integer) o;
} catch (Exception e2) {
try {
String s = (String) o;
v = Integer.parseInt(s);
} catch (Exception e3) {
v = 0;
}
}
}
return v;
}
public int getInt(Object key, int def) {
Object o = get(key);
int v;
try {
v = (int) o;
} catch (Exception e1) {
try {
v = (Integer) o;
} catch (Exception e2) {
try {
String s = (String) o;
v = Integer.parseInt(s);
} catch (Exception e3) {
v = def;
}
}
}
return v;
}
public long getLong(Object key) {
Object o = get(key);
long v;
try {
v = (long) o;
} catch (Exception e1) {
try {
v = (Long) o;
} catch (Exception e2) {
try {
String s = (String) o;
v = Long.parseLong(s);
} catch (Exception e3) {
v = 0;
}
}
}
return v;
}
public long getLong(Object key, long def) {
Object o = get(key);
long v;
try {
v = (long) o;
} catch (Exception e1) {
try {
v = (Long) o;
} catch (Exception e2) {
try {
String s = (String) o;
v = Long.parseLong(s);
} catch (Exception e3) {
v = def;
}
}
}
return v;
}
public Date getDate(Object key) {
Date v;
try {
v = (Date) get(key);
} catch (Exception e) {
v = new Date();
}
return v;
}
public Date getDate(Object key, Date def) {
Date v;
try {
v = (Date) get(key);
} catch (Exception e) {
v = def;
}
return v;
}
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
return map.put(key, value);
}
@SuppressWarnings("unchecked")
@Override
public Object putIfAbsent(Object key, Object value) {
return map.putIfAbsent(key, value);
}
@Override
public Object getOrDefault(Object key, Object defaultValue) {
return map.getOrDefault( key, defaultValue);
}
@Override
public Object remove(Object key) {
return map.remove(key);
}
@Override
public Object replace(Object key, Object value) {
return map.replace( key, value);
}
@Override
public boolean replace(Object key, Object oldValue, Object newValue) {
return map.replace( key, oldValue,newValue);
}
public void clear() {
map.clear();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public Set entrySet() {
return map.entrySet();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Set keySet() {
return map.keySet();
}
@SuppressWarnings("unchecked")
public void putAll(Map t) {
map.putAll(t);
}
public int size() {
return map.size();
}
public Collection values() {
return map.values();
}
}
Controller
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 8:19 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "get", method = RequestMethod.GET, produces = "application/json;charset=UTF-8" )
public ResultVo category() {
List<PageData> list = testService.selectList();
return ResultUtil.getOk(list);
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 2:06 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@RestController
@RequestMapping("testOther")
public class TestOtherController {
private static Logger logger = LoggerFactory.getLogger(TestOtherController.class);
@Autowired
private TestOtherService testOtherService;
@RequestMapping(value = "get", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public ResultVo category() {
logger.debug("======================category");
List<PageData> list = null;
try {
list = testOtherService.selectList();
} catch (Exception e) {
e.printStackTrace();
ResultUtil.getFail();
}
return ResultUtil.getOk(list);
}
@RequestMapping(value = "list", method = RequestMethod.GET)
public ResultVo list() {
Page page = new Page();
PageData pd = new PageData();
pd.put("name", null);
page.setPd(pd);
try {
page = testOtherService.TestListPage(page);
} catch (Exception e) {
e.printStackTrace();
ResultUtil.getFail();
}
return ResultUtil.getOk(page);
}
}
service
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 1:57 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
public interface TestOtherService {
List<PageData> selectList() throws Exception;
Page TestListPage(Page page)throws Exception;
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 8:15 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
public interface TestService {
List<PageData> selectList();
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 1:58 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Service
public class TestOtherServiceImpl implements TestOtherService {
@Autowired
private DaoSupport daoSupport;
private final static String TEST_OTHER_MAPPER = "TestOtherMapper.";
private static final String TagCorpRelation = " TestOther::";
private static final int ExpireCorpRelation = 3600 * 24;
@Override
public List<PageData> selectList() throws Exception {
return (List<PageData>) CacheUtils.fetch(TagCorpRelation + "::", () -> {
return daoSupport.findForList(TEST_OTHER_MAPPER+"selectList", null);
}, ExpireCorpRelation);
}
@Override
public Page TestListPage(Page page) throws Exception {
Object obj=daoSupport.findForList(TEST_OTHER_MAPPER+"testListPage", page);
page.setContent(obj);
return page;
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 8:15 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List<PageData> selectList() {
return testMapper.selectList();
}
}
mapper
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 8:09 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Repository
public interface TestMapper {
List<PageData> selectList();
}
DAO
package com.Logos.dao;
/**
* @author
* 修改时间:
*/
public interface DAO {
/**
* 保存对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object save(String str, Object obj) throws Exception;
/**
* 修改对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object update(String str, Object obj) throws Exception;
/**
* 删除对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object delete(String str, Object obj) throws Exception;
/**
* 查找对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForObject(String str, Object obj) throws Exception;
/**
* 查找对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForList(String str, Object obj) throws Exception;
/**
* 查找对象封装成Map
* @param sql
* @param obj
* @return
* @throws Exception
*/
public Object findForMap(String sql, Object obj, String key, String value) throws Exception;
}
DaoSupport
/**
* @author
* 修改时间:
*/
@Repository
public class DaoSupport implements DAO {
// private SqlSessionFactory sqlSessionFactory;
// SqlSession session = sqlSessionFactory.openSession();
@Resource(name="sqlSessionTemplate")
private SqlSessionTemplate sqlSessionTemplate ;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
/**
* 保存对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object save(String str, Object obj) throws Exception {
return sqlSessionTemplate.insert(str, obj);
}
/**
* 批量更新
* @param str
* @param
* @return
* @throws Exception
*/
public Object batchSave(String str, List objs )throws Exception{
return sqlSessionTemplate.insert(str, objs);
}
/**
* 修改对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object update(String str, Object obj) throws Exception {
return sqlSessionTemplate.update(str, obj);
}
/**
* 批量更新
* @param str
* @param
* @return
* @throws Exception
*/
public void batchUpdate(String str, List objs )throws Exception{
SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
//批量执行器
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
try{
if(objs!=null){
for(int i=0,size=objs.size();i<size;i++){
sqlSession.update(str, objs.get(i));
}
sqlSession.flushStatements();
sqlSession.commit();
sqlSession.clearCache();
}
}finally{
sqlSession.close();
}
}
/**
* 批量更新
* @param str
* @param
* @return
* @throws Exception
*/
public Object batchDelete(String str, List objs )throws Exception{
return sqlSessionTemplate.delete(str, objs);
}
/**
* 删除对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object delete(String str, Object obj) throws Exception {
return sqlSessionTemplate.delete(str, obj);
}
/**
* 查找对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForObject(String str, Object obj) throws Exception {
return sqlSessionTemplate.selectOne(str, obj);
}
/**
* 查找对象
* @param str
* @param obj
* @return
* @throws Exception
*/
public Object findForList(String str, Object obj) throws Exception {
return sqlSessionTemplate.selectList(str, obj);
}
public Object findForMap(String str, Object obj, String key, String value) throws Exception {
return sqlSessionTemplate.selectMap(str, obj, key);
}
}
configuration 配置 拦截器 redis mybatis
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 6:09 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@WebFilter(urlPatterns = "/*", filterName = "LogosFilter")
public class LogosFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("cost="+(System.currentTimeMillis()-start));
}
@Override
public void destroy() {
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 5:31 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Component
public class LogosInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(LogosInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
logger.info("============================拦截器启动==============================");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
logger.info("===========================执行处理完毕=============================");
long starttime = (long) request.getAttribute("starttime");
request.removeAttribute("starttime");
long endtime = System.currentTimeMillis();
logger.info("============请求地址:"+request.getRequestURI()+":处理时间:{}",(endtime-starttime)+"ms");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
logger.info("============================拦截器关闭==============================");
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 5:30 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Configuration
public class LogosInterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogosInterceptor()).addPathPatterns("/**");
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 12:17 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
private static Logger log = LoggerFactory.getLogger(MyBatisConfig.class);
@Value("${druid.driver}")
private String driverClassName;
@Value("${druid.url}")
private String url;
@Value("${druid.username}")
private String username;
@Value("${druid.password}")
private String password;
@Value("${druid.init-size}")
private int initSize;
@Value("${druid.min-idel}")
private int minIdel;
@Value("${druid.max-active}")
private int maxActive;
@Value("${druid.login.timeout.seconds}")
private int loginTimeoutSeconds;
@Value("${druid.query.timeout.seconds}")
private int queryTimeoutSeconds;
@Value("${druid.mappers}")
private String mappers;
@Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setInitialSize(initSize);
ds.setMinIdle(minIdel);
ds.setMaxActive(maxActive);
ds.setLoginTimeout(loginTimeoutSeconds);
ds.setQueryTimeout(queryTimeoutSeconds);
return ds;
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource());
bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources(mappers));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 12:28 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.Logos.mapper");
return mapperScannerConfigurer;
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 5:07 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Configuration
@Import({RedisConfig.class, CacheUtils.class})
public class RedisAutoConfiguration {
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 3:38 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Configuration
@EnableCaching//开启缓存
public class RedisConfig extends CachingConfigurerSupport {
private Logger LOG = LoggerFactory.getLogger(RedisConfig.class);
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
cacheManager.setDefaultExpiration(10000);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);//设置序列化工具
template.afterPropertiesSet();
return template;
}
//序列化定义
private void setSerializer(StringRedisTemplate template){
@SuppressWarnings({ "rawtypes", "unchecked" })
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
cache
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/21 5:24 PM
* @version: V1.0
*/
public class CacheUtils {
@Resource
private RedisTemplate<String, String> redisTemplate;
private static CacheUtils cacheUtils;
@PostConstruct
public void init() {
cacheUtils = this;
cacheUtils.redisTemplate = this.redisTemplate;
}
/**
* @param keys
*/
public static long del(final String... keys) {
return (long) cacheUtils.redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
long result = 0;
for (int i = 0; i < keys.length; i++) {
result = connection.del(keys[i].getBytes());
}
return result;
}
});
}
/**
* @param key
* @param value
* @param liveTime
*/
public static void set(final byte[] key, final byte[] value, final long liveTime) {
cacheUtils.redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
connection.set(key, value);
if (liveTime > 0) {
connection.expire(key, liveTime);
}
return 1L;
}
});
}
/**
* @param key
* @param value
* @param liveTime
*/
public static void set(String key, String value, long liveTime) {
set(key.getBytes(), value.getBytes(), liveTime);
}
/**
* @param key
* @param value
*/
public static void set(String key, String value) {
set(key, value, 0L);
}
/**
* @param key
* @param value
*/
public static void set(byte[] key, byte[] value) {
set(key, value, 0L);
}
/**
* @param key
* @return
*/
public static boolean exists(final String key) {
return (boolean) cacheUtils.redisTemplate.execute(new RedisCallback() {
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.exists(key.getBytes());
}
});
}
/**
* @return
*/
public static String flushDB() {
return (String) cacheUtils.redisTemplate.execute(new RedisCallback() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}
/**
* @return
*/
public static long dbSize() {
return (long) cacheUtils.redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.dbSize();
}
});
}
/**
* @return
*/
public static String ping() {
return (String) cacheUtils.redisTemplate.execute(new RedisCallback() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
return connection.ping();
}
});
}
/**
* 添加key value 并且设置存活时间(byte)
*
* @param key
* @param value
* @param liveTime
*/
public static void add(String key, Object value, int liveTime) {
set(key.getBytes(), ObjectUtil.toByteArray(value), liveTime);
}
public static Object fetch(String key, CacheProvider provider, int liveTime) {
return fetch(key.getBytes(), provider, liveTime);
}
public static Object fetch(String key, CacheProvider provider) {
return fetch(key.getBytes(), provider);
}
public static Object fetch(byte[] key, CacheProvider provider, int liveTime) {
Object obj = null;
byte[] value = null;
value = get(key);
if (null != value) {
return ObjectUtil.toObject(value);
}
if (null != provider) {
try {
obj = provider.getDate();
} catch (Exception e) {
e.printStackTrace();
}
if (null != obj) {
value = ObjectUtil.toByteArray(obj);
if (null != value) {
if (liveTime > 0) {
set(key, value, liveTime);
} else {
set(key, value);
}
}
}
}
return obj;
}
/**
* @Title fetch
* @Authour jxc
* @Parameters [key, provider]
* @Return java.lang.Object
* @Date 2017/11/6 18:13
* @Description: redisFetch无存活时间
* @version V1.0
*/
public static Object fetch(byte[] key, CacheProvider provider) {
Object obj = null;
byte[] value = null;
value = get(key);
if (null != value) {
return ObjectUtil.toObject(value);
}
if (null != provider) {
try {
obj = provider.getDate();
} catch (Exception e) {
e.printStackTrace();
}
if (null != obj) {
value = ObjectUtil.toByteArray(obj);
if (null != value) {
set(key, value);
}
}
}
return obj;
}
/**
* @param key
* @return
*/
public static Object get(final String key) {
return (Object) cacheUtils.redisTemplate.execute(new RedisCallback() {
public Object doInRedis(RedisConnection connection) throws DataAccessException {
return ObjectUtil.toObject(connection.get(key.getBytes()));
}
});
}
/**
* 获取redis value (byte [] )(反序列化)
*
* @param key
* @return
*/
public static byte[] get(byte[] key) {
return (byte[]) cacheUtils.redisTemplate.execute(new RedisCallback() {
public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
return connection.get(key);
}
});
}
/**
* 添加key value
*
* @param key
* @param value
*/
public static void add(String key, String value) {
set(key.getBytes(), ObjectUtil.toByteArray(value));
}
/**
* 通过正则匹配keys
*
* @param pattern
* @return
*/
public static Set<String> keys(String pattern) {
Set<String> stringSet = cacheUtils.redisTemplate.keys(pattern);
return stringSet;
}
public static void delKeys(String patten) {
Set<String> keys = keys(patten);
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String keyStr = it.next();
del(keyStr);
}
}
public static void delKeys(String[] pattens) {
for (String pattern : pattens) {
delKeys(pattern);
}
}
}
/**
* Created by jxc on 2017/3/29.
*/
public interface CacheProvider {
public Object getDate()throws Exception;
}