idea springBoot+mybatis+Redis+Mysql(一)
修改pom.xml文件
org.springframework.boot
spring-boot-starter-parent
1.5.1.RELEASE
4.0.0
SpringBoot
SpringBoot
1.0-SNAPSHOT
1.8
2.8.0
2.3.9
org.springframework.boot
spring-boot-starter-redis
1.4.7.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
org.apache.tomcat.embed
tomcat-embed-jasper
org.mybatis
mybatis
3.4.2
org.mybatis
mybatis-spring
1.3.1
mysql
mysql-connector-java
com.alibaba
druid
1.0.27
com.github.pagehelper
pagehelper
4.1.6
org.springframework.boot
spring-boot-starter-tomcat
provided
com.google.code.gson
gson
${gson.version}
net.iharder
base64
${net.iharder.base64.version}
com.lowagie
itext
2.1.7
org.apache.poi
poi
3.17
commons-collections
commons-collections
3.2.1
org.apache.shiro
shiro-core
1.4.0-RC2
commons-io
commons-io
2.5
org.freemarker
freemarker
2.3.25-incubating
com.belerweb
pinyin4j
2.5.1
com.aliyun.oss
aliyun-sdk-oss
2.5.0
commons-fileupload
commons-fileupload
1.2.2
com.esotericsoftware.kryo
kryo
2.24.0
de.ruedigermoeller
fst
2.57
com.aliyun
aliyun-java-sdk-core
3.2.2
org.apache.poi
poi-ooxml
3.17
com.aliyun
aliyun-java-sdk-push
3.0.0
com.aliyun.mns
aliyun-sdk-mns
1.1.8
org.quartz-scheduler
quartz
2.2.3
com.aliyun
aliyun-java-sdk-ram
2.0.7
com.alibaba
fastjson
1.2.3
com.aliyun
aliyun-java-sdk-sts
2.1.6
org.codehaus.jackson
jackson-mapper-asl
1.9.13
junit
junit
test
org.springframework
spring-test
4.1.4.RELEASE
org.springframework.data
spring-data-redis
1.7.1.RELEASE
redis.clients
jedis
2.8.2
war
SpringBoot
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-war-plugin
2.1.1
false
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
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
testOther
id,
name
#{id},
#{name}
insert into
(
) values (
)
update
set name = #{name}
where
id = #{id}
delete from
where
id = #{id}
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
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();
}
}
/**
* @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 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 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);
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/19 1:57 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
public interface TestOtherService {
List 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 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 selectList() throws Exception {
return (List) 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 selectList() {
return testMapper.selectList();
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/18 8:09 PM
* @version: V1.0
* @Software: IntelliJ IDEA
*/
@Repository
public interface TestMapper {
List selectList();
}
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;
}
/**
* @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
/**
* @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 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);
}
}
/**
* @Description: TODO
* @author: jxc
* @date: 2019/6/21 5:24 PM
* @version: V1.0
*/
public class CacheUtils {
@Resource
private RedisTemplate 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 keys(String pattern) {
Set stringSet = cacheUtils.redisTemplate.keys(pattern);
return stringSet;
}
public static void delKeys(String patten) {
Set keys = keys(patten);
Iterator 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;
}
框架源码地址