Redis缓存分页
Redis 缓存分页封装
·
工具类
@Component
public class RedisPageUtils {
@Autowired
private RedisTemplate<String, Object> stringredisTemplate;
/**
* 创建 分页数据
* @param zsetName zset名称
* @param id 分值/id
* @param str 需要返回的数据
*/
public void addCach(String zsetName, Long id,String str) {
String hashName=zsetName+"Hash";
//创建zset
zSetAdd(zsetName,id,String.valueOf(id));
//创建hash
hSetAdd(hashName,String.valueOf(id),str);
}
/**
* 获取分页数据
* @param zsetName zset名称
* @param pages 页数
* @param size 每页条数
* @param t 返回的对象
* @return
*/
public LayuiPageInfo getCachList(String zsetName, Integer pages, Integer size, Object t){
String hashName=zsetName+"Hash";
//获取总条数
long toal = zSetToal(zsetName);
//总页数
Long totalPage = setsearchCount(toal, Long.valueOf(size));
//获取最大分值
double maxScore = maxScore(zsetName);
//获取zset的区间
Set limit = zSetLimit(zsetName, 0, maxScore, (pages - 1) * size, size);
//根据zset的区间获取 hash的集合
List addHashComStore = hsetGetList(hashName, limit);
net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject( addHashComStore);
List<T> list1 = (List) net.sf.json.JSONArray.toCollection(jsonArray,t.getClass());
return LayuiPageInfo.createPageInfo(list1,Integer.valueOf(String.valueOf(toal)),Integer.valueOf(String.valueOf(totalPage)));
}
/**
* 根据id 删除 zset 、hash中的数据
* @param zsetName
* @param id
*/
public void delALl(String zsetName, Integer id){
String hashName=zsetName+"Hash";
zSetDel(zsetName,id);
hSetdel(hashName,String.valueOf(id));
}
/**
* Redis Zadd 命令用于将一个元素及其分数值加入到有序集当中。
* @param name zset名称
* @param score 分数
* @param value 值
*/
public void zSetAdd(String name,double score,String value){
stringredisTemplate.opsForZSet().add(name,value,score);
}
/**
* Zset 根据分值删除其中一个
* @param name zset名称
* @param score 分数
*/
public void zSetDel(String name,double score){
stringredisTemplate.opsForZSet().removeRangeByScore(name,score,score);
}
public Double maxScore(String name){
Set<Object> sortId = stringredisTemplate.opsForZSet().reverseRange(name, 0, 0);
if(sortId.size()==0){
return 0d;
}else {
String hkey = String.valueOf(sortId.iterator().next());
//根据member获得最大分值
Double maxScore = stringredisTemplate.opsForZSet().score(name, hkey);
return maxScore;
}
}
/**
* zSet 获取总条数
* @param name
*/
public long zSetToal(String name){
long count = stringredisTemplate.opsForZSet().zCard(name);
return count;
}
/**
* zSet 根据设置的score获取区间值从给定下标和给定长度获取最终值。
* @param key
* @param min
* @param max
* @param offset
* @param count
* @return
*/
public Set zSetLimit(String key, double min, double max,long offset, long count){
Set zSetValue = stringredisTemplate.opsForZSet().rangeByScore(key, min, max, offset, count);
return zSetValue;
}
/**
* 哈希 新增hashMap值
* @param key hset名称
* @param hashKey key
* @param value 值
*/
public void hSetAdd(String key,String hashKey,String value){
stringredisTemplate.opsForHash().put(key,hashKey,value);
}
/**
* 哈希 根据hashKey 删除
* @param key
* @param hashKey
*/
public void hSetdel(String key,String hashKey){
stringredisTemplate.opsForHash().delete(key,hashKey);
}
public List hsetGetList(String key, Collection list){
List mapValueList = stringredisTemplate.opsForHash().multiGet(key,list);
return mapValueList;
}
public static Long setsearchCount(Long searchCount,Long size) {
//页数根据传入的总行数以及每页显示的行数,求出总页数
return searchCount % size == 0 ? searchCount / size : (searchCount / size + 1);
}
}
测试
@Api(description = "任务API")
@RestController
@RequestMapping("/apitest/test")
@Validated
public class testAPI {
private static final Logger log = LoggerFactory.getLogger(testAPI.class);
@Autowired
private SysUserAdminService adminService;
@Autowired
private RedisPageUtils redisPageUtils;
@ApiOperation(value = "删除 ")
@ApiImplicitParams({
@ApiImplicitParam(value = "(必传)token", name = "token", dataType = "String", required = true, paramType = "header"),
@ApiImplicitParam(value = "(必传)id", name = "id", dataType = "Integer", required = true, paramType = "query"),
})
@ApiResponses(value = {
@ApiResponse(code = 0000, message = "请求已完成"),
@ApiResponse(code = 0001, message = "操作失败"),
@ApiResponse(code = 112, message = "未查询到数据"),
})
@RequestMapping(value = "/del", method = RequestMethod.POST)
@ResponseBody
@MethodMonitor
public LayuiPageInfo del(@RequestParam(value = "id") Integer id ) {
String zsetName="addZSETComStore";
redisPageUtils.delALl(zsetName,id);
return LayuiPageInfo.createPageInfoError(0,"ok");
}
@ApiOperation(value = "获取列表")
@ApiImplicitParams({
@ApiImplicitParam(value = "(必传)token", name = "token", dataType = "String", required = true, paramType = "header"),
@ApiImplicitParam(value = "(必传)页数", name = "pages", dataType = "int", required = true, paramType = "query"),
})
@ApiResponses(value = {
@ApiResponse(code = 0000, message = "请求已完成"),
@ApiResponse(code = 0001, message = "操作失败"),
@ApiResponse(code = 400, message = "参数检验不符合规则"),
})
@RequestMapping(value = "/getList", method = RequestMethod.POST)
@ResponseBody
@MethodMonitor
public LayuiPageInfo<Page<CommuntityPatrolRuleProject>> getList(
@RequestParam(value = "pages", defaultValue = "1") @Min(value = 1, message = "页数 不能为空") Integer pages) {
Page<CommuntityPatrolRuleProject> page = new Page<>();
int size = 5;
page.setSize(size);
page.setCurrent(pages);
String zsetName="addZSETComStore";
LayuiPageInfo cachList = redisPageUtils.getCachList(zsetName, pages, size, new CommuntityPatrolRuleProject());
return cachList;
}
@ApiOperation(value = "list初始化")
@ApiImplicitParams({
@ApiImplicitParam(value = "(必传)token", name = "token", dataType = "String", required = true, paramType = "header"),
@ApiImplicitParam(value = "(必传)id", name = "id", dataType = "int", required = true, paramType = "query"),
})
@ApiResponses(value = {
@ApiResponse(code = 0000, message = "请求已完成"),
@ApiResponse(code = 0001, message = "操作失败"),
@ApiResponse(code = 400, message = "参数检验不符合规则"),
})
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
@MethodMonitor
public LayuiPageInfo test(@RequestParam(value = "id", defaultValue = "1") Integer id) throws Exception {
MyEntityWrapper<SysUserAdmin> entityWrapper = new MyEntityWrapper<>();
entityWrapper.eq("id",id);
List<SysUserAdmin> list = adminService.selectList(entityWrapper);
String zsetName="addZSETComStore";
for (SysUserAdmin admin : list) {
redisPageUtils.addCach(zsetName,Long.valueOf(admin.getId()),JSONObject.toJSONString(admin));
}
return LayuiPageInfo.createPageInfoError(0,"ok");
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LayuiPageInfo<T> {
private static Long size=20l; // 每页显示的行数,需要传参
public static Long setsearchCount(Long searchCount) {
//页数根据传入的总行数以及每页显示的行数,求出总页数
return searchCount % size == 0 ? searchCount / size : (searchCount / size + 1);
}
@ApiModelProperty(value = "返回码", dataType = "String")
private Integer code=0;
@ApiModelProperty(value = "响应提示")
private String msg = "请求成功"; ;
@ApiModelProperty(value ="数据")
private List<T> data;
@ApiModelProperty(value ="map")
private Map<String,Object> totalRow;
@ApiModelProperty(value ="object")
public Object object;
@ApiModelProperty(value ="count")
private Integer count;
@ApiModelProperty(value ="totalpages")
private Integer totalpages;
private String score;
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public void setResultStatus(Integer code, String msg ){
this.code = code;
this.msg = msg;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getTotalpages() {
return totalpages;
}
public void setTotalpages(Integer totalpages) {
this.totalpages = totalpages;
}
public Map<String, Object> getTotalRow() {
return totalRow;
}
public void setTotalRow(Map<String, Object> totalRow) {
this.totalRow = totalRow;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public static LayuiPageInfo createPageInfo(List list,Integer count,Integer totalpages) {
LayuiPageInfo result = new LayuiPageInfo();
result.setCount(count);
result.setTotalpages(totalpages);
result.setData(list);
return result;
}
public static LayuiPageInfo createPageInfoError(Integer code,String msg) {
LayuiPageInfo result = new LayuiPageInfo();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
更多推荐
已为社区贡献3条内容
所有评论(0)