概述
上节主要讲解SpringBoot项目框架搭建,这里不再赘述。内容建立在上节基础上,具体详情地址:http://blog.csdn.net/fjekin/article/details/78407153,本篇介绍MybatisPlus分页和Redis的使用。
分页测试(效果图)
笔者用的接口测试工具是谷歌的apizza,也是蛮强大的。减少文档编写工作量。
分页
排序规则,Order.java
package com.jekin.example.entity.page;
/**
* 数据库排序
*
*
* @Date 2017年5月31日20:48:41
*/
public enum Order {
ASC("asc" ), DESC("desc" );
private String des;
Order(String des) {
this .des = des;
}
public String getDes () {
return des;
}
public void setDes (String des) {
this .des = des;
}
}
分页结果封装,PageInfoBT.java
package com.jekin.example.entity.page;
import java.util.List;
import com.baomidou.mybatisplus.plugins.Page;
public class PageInfoBT {
private List content;
private long total;
public PageInfoBT (Page page) {
this .content = page.getRecords();
this .total = page.getTotal();
}
public List getContent () {
return content;
}
public void setContent (List content) {
this .content = content;
}
public long getTotal () {
return total;
}
public void setTotal (long total) {
this .total = total;
}
}
接口请求默认分页配置,PageFactory.java
package com .jekin .example .factory
import javax.servlet .http .HttpServletRequest
import org.apache .commons .lang 3.StringUtils
import org.springframework .web .context .request .RequestContextHolder
import org.springframework .web .context .request .ServletRequestAttributes
import com .baomidou .mybatisplus .plugins .Page
import com .jekin .example .entity .page .Order
public class PageFactory {
public Page defaultPage() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()).getRequest ()
int size = 12
int current = 0
if (!StringUtils.isEmpty (request.getParameter ("size" ))) {
size = Integer.valueOf (request.getParameter ("size" ))
current = Integer.valueOf (request.getParameter ("page" ))
} else {
size = 60000
current = 0
}
String sort = request.getParameter ("sort" )
String order = request.getParameter ("order" )
if (StringUtils.isEmpty (sort)) {
Page page = new Page<>(current, size)
page.setOpenSort (false)
return page
} else {
Page page = new Page<>(current, size, sort)
if (Order.ASC .getDes ().equals (order)) {
page.setAsc (true)
} else {
page.setAsc (false)
}
return page
}
}
}
使用例子,UserController.java
package com .jekin .example .controller
import java.util .List
import javax.annotation .Resource
import org.springframework .stereotype .Controller
import org.springframework .web .bind .annotation .RequestMapping
import org.springframework .web .bind .annotation .ResponseBody
import com .baomidou .mybatisplus .plugins .Page
import com .jekin .example .entity .ResultInfo
import com .jekin .example .entity .User
import com .jekin .example .entity .page .PageInfoBT
import com .jekin .example .factory .PageFactory
import com .jekin .example .mapper .UserMapper
@Controller
@RequestMapping(value = "/redis/user" )
public class UserController {
@Resource
private UserMapper userMapper
@RequestMapping("/list" )
@ResponseBody
public ResultInfo list(
) {
Page page = new PageFactory().defaultPage ()
List result = userMapper.getUserPage (page,
page.getOrderByField (), page.isAsc ())
page.setRecords (result)
ResultInfo resultInfo = new ResultInfo(0 , "success" )
resultInfo.setData (new PageInfoBT(page))
return resultInfo
}
}
默认,分页参数可不传,ResultInfo是对结果集的包装。 Dao方法,UserMapper.java
List getUserPage(@Param ("page" ) Page page,
@Param ("orderByField" ) String orderByField, @Param ("isAsc" ) boolean isAsc);
映射文件,UserMapper.xml
<mapper namespace ="com.jekin.example.mapper.UserMapper" >
<sql id ="Base_Column_List" >
id,type,openid,avatar,account,password,salt,name,birthday,sex,email,phone,roleid,status,createtime,updatetime,balance
sql >
<resultMap id ="BaseResultMap" type ="User" >
<id column ="id" property ="id" />
<result column ="type" property ="type" />
<result column ="openid" property ="openid" />
<result column ="avatar" property ="avatar" />
<result column ="account" property ="account" />
<result column ="password" property ="password" />
<result column ="salt" property ="salt" />
<result column ="name" property ="name" />
<result column ="birthday" property ="birthday" />
<result column ="sex" property ="sex" />
<result column ="email" property ="email" />
<result column ="phone" property ="phone" />
<result column ="roleid" property ="roleid" />
<result column ="status" property ="status" />
<result column ="createtime" property ="createtime" />
<result column ="updatetime" property ="updatetime" />
<result column ="balance" property ="balance" />
resultMap >
<select id ="getUserPage" resultType ="User" >
select <include refid ="Base_Column_List" /> from user where 1 = 1
<choose >
<when test ="orderByField != null and orderByField !=''" >
<choose >
<when test ="isAsc == true" >
order by ${orderByField} ASC
when >
<otherwise >
order by ${orderByField} DESC
otherwise >
choose >
when >
<otherwise >
order by id DESC
otherwise >
choose >
select >
mapper >
以上重点是PageFactory类,笔者在MP分页辅助类Page上又一次包装,通过HttpServletRequest获取接口参数做初始化工作。关于MP更多内容,可以查看官网地址,笔者建议直接查看源码,里面都有中文注释,比官网介绍的更详细。
Redis缓存
引入jar包,配置地址等参数(上节有写,不赘述)。序列和反序列化,FastJson2JsonRedisSerializer.java
package com.jekin.example.config;
import java.nio.charset.Charset;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class FastJson2JsonRedisSerializer <T > implements RedisSerializer <T > {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8" );
private Class clazz;
public FastJson2JsonRedisSerializer(Class clazz) {
super ();
this .clazz = clazz;
}
public byte [] serialize(T t) throws SerializationException {
if (t == null ) {
return new byte [0 ];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
public T deserialize(byte [] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0 ) {
return null ;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str , clazz);
}
}
注解方式实例化,RedisConfig.java
package com.jekin.example.config;
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 使用@Cacheable注解,修改key的生成策略
*
* @return
*/
@Bean
public KeyGenerator keyGenerator () {
return new KeyGenerator() {
@Override
public Object generate (Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 管理缓存
*/
@SuppressWarnings ("rawtypes" )
@Bean
public CacheManager cacheManager (RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
return rcm;
}
@Bean
@SuppressWarnings ("rawtypes" )
public RedisSerializer fastJson2JsonRedisSerializer () {
return new FastJson2JsonRedisSerializer(Object.class);
}
/**
* RedisTemplate配置
*/
@Bean
@SuppressWarnings ("rawtypes" )
public RedisTemplate redisTemplate (RedisConnectionFactory factory,
RedisSerializer fastJson2JsonRedisSerializer) {
StringRedisTemplate template = new StringRedisTemplate(factory);
template.setValueSerializer(fastJson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
重写配置缓存,keyGenerator()是当使用@Cacheable注解时,自动生成key策略,不用可以去掉。 对外接口类,RedisService.java
package com.jekin.example.service;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* redis 服务接口类
*
* @author fengjk
* @date 2017年10月13日
* @since 1.0
*/
public interface RedisService {
/**
* 从指定的列表右边出队,添加到目的列表中
*
* @param srckey 源列表
* @param dstkey 目的列表
* @return
*/
public String rpoppush (String srckey, String dstkey);
/**
* 获取指定列表的范围数据
*
* @param key 列表名
* @param start 开始位置
* @param end 结束位置
* @return
*/
public List lrange (String key, int start, int end);
/**
* 从队列的左边取出一条数据
*
* @param key 列表名
* @return
*/
public String lpop (String key);
/**
* 从队列的左边取出一条数据
*
* @param key 列表名
* @return
*/
public List> lpop (String key, long size);
/**
* 从列表右边添加数据
*
* @param key 列表名
* @param values 数据
* @return
*/
public long rpush (String key, String... values);
/**
* 从列表右边添加数据
*
* @param key 列表名
* @param values 数据
* @return
*/
public long rpush (String key, Collection values);
public int hmset (String key, Map values);
/**
*
* @Title : hgetAll
* @user : zzx
* @time : 2016年11月17日上午9:05:10 //DESC 返回哈希表 key 中,所有的域和值
* @param key
* @return
* @return Map 返回类型
* @throws
*/
public Map hgetAll (String key);
public int hput (String key, String hashKey, String value);
public String hget (String key, String field);
public List> hkeys (String key);
/**
* 删除hash表中field
*/
public void hdel (String key, String field);
/**
* 从列表右边添加数据,并且设置列表的存活时间
*
* @param key 列表名
* @param liveTime 存活时间(单位 秒)
* @param values 数据
* @return
*/
public long rpush (String key, int liveTime, String... values);
/**
* 从队列的右边取出一条数据
*
* @param key 列表名
* @return
*/
public String rpop (String key);
/**
* 把一个值添加到对应列表中
*
* @param key 列表名
* @param index 添加的位置
* @param value 数据
* @return
*/
public String lset (String key, long index, String value);
/**
* 把所有数据添加到一个列表中
*
* @param key 列表名
* @param values 数据
* @return
*/
public long lpush (String key, String... values);
/**
* 把所有数据添加到一个列表中,并且设置列表的存活时间
*
* @param key 列表名
* @param values 数据
* @param liveTime 存活时间--单位(秒)
* @return
*/
public long lpush (String key, long liveTime, String... values);
/**
* 返回列表的长度
*
* @param key
* @return
*/
public long llen (String key);
/**
* 删除列表中对应值的元素
*
* @param key 列表名
* @param count 删除多少个相同的元素
* @param value 数据
* @return
*/
public long lrem (String key, long count, String value);
/**
* 通过keys批量删除
*
* @param key
*/
public long del (String... keys);
/**
* 通过keys批量删除
*
* @param key
*/
public long del (List keys);
/**
*
* //DESC 删除单个key
*
* @time : 2016年5月27日 上午9:00:36
* @param key
* @return
* @throws
*/
public long del (String key);
/**
* 添加key value 并且设置存活时间(byte)
*
* @param key
* @param value
* @param liveTime
*/
public void set (byte [] key, byte [] value, long liveTime);
/**
* 添加key value 并且设置存活时间
*
* @param key
* @param value
* @param liveTime 单位秒
*/
public void set (String key, String value, long liveTime);
/**
* 添加key value
*
* @param key
* @param value
*/
public void set (String key, String value);
/**
* 添加key value
*
* @param key
* @param value
*/
public void setMulti (Map map);
/**
* 添加key value
*
* @param key
* @param value
*/
public void setMulti (Map map, long liveTime);
/**
* 添加key value (字节)(序列化)
*
* @param key
* @param value
*/
public void set (byte [] key, byte [] value);
/**
* 获取redis value (String)
*
* @param key
* @return
*/
public String get (String key);
/**
* 如果key不存在添加key value 并且设置存活时间(byte),当key已经存在时,就不做任何操作
*
* @param key
* @param value
* @param liveTime
*/
public long setnx (byte [] key, byte [] value, long liveTime);
/**
* 如果key不存在添加key value 并且设置存活时间,当key已经存在时,就不做任何操作
*
* @param key
* @param value
* @param liveTime 单位秒
*/
public long setnx (String key, String value, long liveTime);
/**
* 如果key不存在添加key value,当key已经存在时,就不做任何操作
*
* @param key
* @param value
*/
public long setnx (String key, String value);
/**
* 如果key不存在添加key value (字节)(序列化),当key已经存在时,就不做任何操作
*
* @param key
* @param value
*/
public long setnx (byte [] key, byte [] value);
/**
* 通过正则匹配keys
*
* @param pattern
* @return
*/
public Set keys (String pattern);
/**
* 检查key是否已经存在
*
* @param key
* @return
*/
public boolean exists (String key);
/**
* 清空redis 所有数据
*
* @return
*/
public String flushDB ();
/**
* 查看redis里有多少数据
*/
public long dbSize ();
/**
* 检查是否连接成功
*
* @return
*/
public String ping ();
/**
* 设置key的生命周期
*
* @param key
* @param seconds 单位(秒)
* @return
*/
public boolean expire (String key, long seconds);
/**
* 自增长
*
* @param key
* @param length 增长步长
* @return
*/
public long incr (String key);
/**
* 自增长
*
* @param key
* @param length 增长步长
* @return
*/
public long incrBy (String key, long len);
/**
* 自增长
*
* @param key
* @param length 增长步长
* @return
*/
public double incrBy (String key, double len);
public long eval (String luaCommand);
/**
* 返回集合中一个或多个随机数 当count大于set的长度时,set所有值返回,不会抛错。 当count等于0时,返回[]
* 当count小于0时,也能返回。如-1返回一个,-2返回两个
*
* @param key
* @param count
* @return List
*/
public Set srandMember (String key, int count);
/**
* 从集合口随机取出一条数据
*
* @param key 集合名
* @return
*/
public String spop (String key);
/**
* 从集合中随机弹出多条数据
*
* @param key 集合名
* @return
*/
public List> spop (String key, int size);
/**
* 移除集合中一个或多个成员
*
* @param key
* @param members
* @return
*/
public Long srem (String key, List values);
/**
* 向集合添加一个或多个成员,返回添加成功的数量
*
* @param key
* @param members
* @return Long
*/
public Long sadd (String key, String... values);
public long sadd (String key, Collection values1);
public int hset (String key, Map value);
}
实现类,RedisServiceImpl.java
package com.jekin.example.service.impl;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jekin.example.service.RedisService;
/**
* redis API
*
* @author fengjk
* @date 2017年10月13日
* @since 1.0
*/
@Service
@Transactional
public class RedisServiceImpl implements RedisService {
private static String redisCode = "utf-8" ;
@Autowired
private RedisTemplate redisTemplate;
/**
*
*
* @author fengjk
* @param srckey
* @param dstkey
* @return
*/
@Override
public String rpoppush (final String srckey, final String dstkey) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
try {
return new String(connection.rPopLPush(srckey.getBytes(), dstkey.getBytes()), redisCode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "" ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param start
* @param end
* @return
*/
@Override
public List lrange (final String key, final int start, final int end) {
return redisTemplate.execute(new RedisCallback>() {
List result = new ArrayList();
public List doInRedis (RedisConnection connection) throws DataAccessException {
List<byte []> bytelist = connection.lRange(key.getBytes(), start, end);
for (byte [] b : bytelist) {
try {
result.add(new String(b, redisCode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public String lpop (final String key) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
byte [] result = connection.lPop(key.getBytes());
if (result != null ) {
try {
return new String(result, redisCode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "" ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param size
* @return
*/
@Override
public List> lpop (final String key, final long size) {
List list = redisTemplate.executePipelined(new RedisCallback>() {
public List doInRedis (RedisConnection connection) throws DataAccessException {
byte [] keyBytes = key.getBytes();
for (int i = 0 ; i < size; i++) {
connection.lPop(keyBytes);
}
return null ;
}
});
list.removeAll(Collections.singleton(null ));
return list;
}
/**
*
*
* @author fengjk
* @param key
* @param values
* @return
*/
@Override
public long rpush (final String key, final String... values) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String v : values) {
result = connection.rPush(key.getBytes(), v.getBytes());
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param values
* @return
*/
@Override
public long rpush (final String key, final Collection values) {
return redisTemplate.opsForList().rightPushAll(key, values);
}
/**
*
*
* @author fengjk
* @param key
* @param values
* @return
*/
@Override
public int hmset (final String key, final Map values) {
try {
redisTemplate.opsForHash().putAll(key, values);
} catch (Exception e) {
e.printStackTrace();
return -1 ;
}
return 0 ;
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public Map hgetAll (final String key) {
return redisTemplate.boundHashOps(key).entries();
}
/**
*
*
* @author fengjk
* @param key
* @param hashKey
* @param value
* @return
*/
@Override
public int hput (final String key, final String hashKey, final String value) {
try {
redisTemplate.opsForHash().put(key, hashKey, value);
} catch (Exception e) {
e.printStackTrace();
return -1 ;
}
return 0 ;
}
/**
*
*
* @author fengjk
* @param key
* @param field
* @return
*/
@Override
public String hget (final String key, final String field) {
Object obj = redisTemplate.opsForHash().get(key, field);
if (obj == null )
return null ;
return String.valueOf(obj);
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public List> hkeys (final String key) {
Set sets = redisTemplate.opsForHash().keys(key);
List list = new ArrayList();
for (Object b : sets) {
list.add(String.valueOf(b));
}
return list;
}
/**
*
*
* @author fengjk
* @param key
* @param field
*/
@Override
public void hdel (final String key, final String field) {
redisTemplate.opsForHash().delete(key, field);
}
/**
*
*
* @author fengjk
* @param key
* @param liveTime
* @param values
* @return
*/
@Override
public long rpush (final String key, final int liveTime, final String... values) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String v : values) {
connection.rPush(key.getBytes(), v.getBytes());
}
if (liveTime > 0 ) {
connection.expire(key.getBytes(), liveTime);
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public String rpop (final String key) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
byte [] result = connection.rPop(key.getBytes());
if (result != null ) {
try {
return new String(result, redisCode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "" ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param index
* @param value
* @return
*/
@Override
public String lset (final String key, final long index, final String value) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
connection.lSet(key.getBytes(), index, value.getBytes());
return "success" ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param values
* @return
*/
@Override
public long lpush (String key, String... values) {
return this .lpush(key, 0 , values);
}
/**
*
*
* @author fengjk
* @param key
* @param liveTime
* @param values
* @return
*/
@Override
public long lpush (final String key, final long liveTime, final String... values) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String v : values) {
result = connection.lPush(key.getBytes(), v.getBytes());
}
if (liveTime > 0 ) {
connection.expire(key.getBytes(), liveTime);
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public long llen (final String key) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.lLen(key.getBytes());
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param count
* @param value
* @return
*/
@Override
public long lrem (final String key, final long count, final String value) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.lRem(key.getBytes(), count, value.getBytes());
}
});
}
/**
*
*
* @author fengjk
* @param keys
* @return
*/
@Override
public long del (final String... keys) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String k : keys) {
result = connection.del(k.getBytes());
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param keys
* @return
*/
@Override
public long del (final List keys) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String k : keys) {
result = connection.del(k.getBytes());
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public long del (final String key) {
return redisTemplate.execute(new RedisCallback() {
@Override
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.del(key.getBytes());
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param value
* @param liveTime
*/
@Override
public void set (final byte [] key, final byte [] value, final long liveTime) {
redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
connection.set(key, value);
if (liveTime > 0 ) {
connection.expire(key, liveTime);
}
return 1 L;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param value
* @param liveTime
*/
@Override
public void set (String key, String value, long liveTime) {
this .set(key.getBytes(), value.getBytes(), liveTime);
}
/**
*
*
* @author fengjk
* @param key
* @param value
*/
@Override
public void set (String key, String value) {
this .set(key, value, 0 L);
}
/**
*
*
* @author fengjk
* @param map
*/
@Override
public void setMulti (final Map map) {
setMulti(map, 0 L);
}
/**
*
*
* @author fengjk
* @param map
* @param liveTime
*/
@Override
public void setMulti (final Map map, final long liveTime) {
redisTemplate.executePipelined(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
Set> set = map.entrySet();
for (Entry entry : set) {
connection.set(entry.getKey().getBytes(), entry.getValue().getBytes());
if (liveTime > 0 ) {
connection.expire(entry.getKey().getBytes(), liveTime);
}
}
return null ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param value
*/
@Override
public void set (byte [] key, byte [] value) {
this .set(key, value, 0 L);
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public String get (final String key) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
byte [] result = connection.get(key.getBytes());
if (result != null ) {
try {
return new String(result, redisCode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "" ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param value
* @param liveTime
* @return
*/
@Override
public long setnx (final byte [] key, final byte [] value, final long liveTime) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 l;
boolean isSuccess = connection.setNX(key, value);
if (isSuccess) {
if (liveTime > 0 ) {
connection.expire(key, liveTime);
}
result = 1 l;
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param value
* @param liveTime
* @return
*/
@Override
public long setnx (String key, String value, long liveTime) {
return this .setnx(key.getBytes(), value.getBytes(), liveTime);
}
/**
*
*
* @author fengjk
* @param key
* @param value
* @return
*/
@Override
public long setnx (String key, String value) {
return this .setnx(key, value, 0 L);
}
/**
*
*
* @author fengjk
* @param key
* @param value
* @return
*/
@Override
public long setnx (byte [] key, byte [] value) {
return this .setnx(key, value, 0 L);
}
/**
*
*
* @author fengjk
* @param pattern
* @return
*/
@Override
public Set keys (final String pattern) {
return redisTemplate.execute(new RedisCallback>() {
public Set doInRedis (RedisConnection connection) throws DataAccessException {
Set result = new HashSet();
Set<byte []> data = connection.keys(pattern.getBytes());
for (byte [] d : data) {
try {
result.add(new String(d, redisCode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public boolean exists (final String key) {
return redisTemplate.execute(new RedisCallback() {
public Boolean doInRedis (RedisConnection connection) throws DataAccessException {
return connection.exists(key.getBytes());
}
});
}
/**
*
*
* @author fengjk
* @return
*/
@Override
public String flushDB () {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "success" ;
}
});
}
/**
*
*
* @author fengjk
* @return
*/
@Override
public long dbSize () {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.dbSize();
}
});
}
/**
*
*
* @author fengjk
* @return
*/
@Override
public String ping () {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
return connection.ping();
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param seconds
* @return
*/
@Override
public boolean expire (final String key, final long seconds) {
return redisTemplate.execute(new RedisCallback() {
public Boolean doInRedis (RedisConnection connection) throws DataAccessException {
return connection.expire(key.getBytes(), seconds);
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public long incr (final String key) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.incr(key.getBytes());
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param len
* @return
*/
@Override
public long incrBy (final String key, final long len) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.incrBy(key.getBytes(), len);
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param len
* @return
*/
@Override
public double incrBy (final String key, final double len) {
return redisTemplate.execute(new RedisCallback() {
public Double doInRedis (RedisConnection connection) throws DataAccessException {
return connection.incrBy(key.getBytes(), len);
}
});
}
/**
*
*
* @author fengjk
* @param luaCommand
* @return
*/
@Override
public long eval (final String luaCommand) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
return connection.eval(luaCommand.getBytes(), null , 0 );
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param count
* @return
*/
@Override
public Set srandMember (final String key, final int count) {
return redisTemplate.execute(new RedisCallback>() {
public Set doInRedis (RedisConnection connection) throws DataAccessException {
Set result = new HashSet();
List<byte []> data = connection.sRandMember(key.getBytes(), count);
for (byte [] d : data) {
try {
result.add(new String(d, redisCode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @return
*/
@Override
public String spop (final String key) {
return redisTemplate.execute(new RedisCallback() {
public String doInRedis (RedisConnection connection) throws DataAccessException {
byte [] result = connection.sPop(key.getBytes());
if (result != null ) {
try {
return new String(result, redisCode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "" ;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param size
* @return
*/
@Override
public List> spop (final String key, final int size) {
List list = redisTemplate.executePipelined(new RedisCallback>() {
public List doInRedis (RedisConnection connection) throws DataAccessException {
byte [] keyBytes = key.getBytes();
for (int i = 0 ; i < size; i++) {
connection.sPop(keyBytes);
}
return null ;
}
});
list.removeAll(Collections.singleton(null ));
return list;
}
/**
*
*
* @author fengjk
* @param key
* @param values
* @return
*/
@Override
public Long srem (final String key, final List values) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String v : values) {
result = connection.sRem(key.getBytes(), v.getBytes());
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param values
* @return
*/
@Override
public Long sadd (final String key, final String... values) {
return redisTemplate.execute(new RedisCallback() {
public Long doInRedis (RedisConnection connection) throws DataAccessException {
long result = 0 ;
for (String v : values) {
result = connection.sAdd(key.getBytes(), v.getBytes());
}
return result;
}
});
}
/**
*
*
* @author fengjk
* @param key
* @param values1
* @return
*/
@Override
public long sadd (final String key, final Collection values1) {
String[] values = (String[]) values1.toArray(new String[values1.size()]);
return redisTemplate.opsForSet().add(key, values);
}
/**
*
* @Description :存放数据信息
* @param key
* @param value
* @return int
* @exception :
* @author : liangcm
* @time :2017年4月27日 下午5:33:05
*/
@Override
public int hset (final String key, final Map value) {
try {
redisTemplate.opsForHash().putAll(key, value);
} catch (Exception e) {
e.printStackTrace();
return -1 ;
}
return 0 ;
}
}
单元测试,RedisTest.java
@RunWith (SpringRunner.class)
@SpringBootTest (classes = RedisExampleApplication.class,webEnvironment=WebEnvironment.RANDOM_PORT)
@ActiveProfiles ("local" )
public class RedisTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisTest.class);
@Autowired
RedisService redisService;
@Autowired
UserMapper userMapper;
@Test
public void testRedis (){
redisService.set("key" , "1" );
String str = redisService.get("key" );
LOGGER.info("key value is:{}" , str);
}
}
这里只做简单的测试,里面做了很多方法的实现,具体方法用途可以查看RedisService接口的注释。
总结
至此,关于SpringBoot项目搭建和MP分页,以及Redis缓存的讲解就到此结束。篇幅有点长,相信看完多多少少对读者都有所收获,这节笔者对代码做了点修改,但并不影响上节陈述的内容。可以加群获取最新代码:583138104。最后,文章如有笔误,麻烦评论留言相告,谢谢! 源码下载