当前位置: 代码网 > it编程>编程语言>Java > springboot集成redis之字典缓存详解

springboot集成redis之字典缓存详解

2024年07月24日 Java 我要评论
什么是redis的字典缓存?redis的缓存是redis内部用于存储键值对数据结构的一种基础数据结构。在redis中,所有的键值对都是通过字典这种数据结构来存储的。字典在redis中扮演着核心角色,因

什么是redis的字典缓存?

redis的缓存是redis内部用于存储键值对数据结构的一种基础数据结构。在redis中,所有的键值对都是通过字典这种数据结构来存储的。字典在redis中扮演着核心角色,因为它不仅用于数据库中的键值对存储,还用于实现其他如哈希、集合等复杂数据结构。
以下是关于redis字典缓存的一些关键点:

  • 数据结构:redis的字典使用哈希表作为底层实现,这样可以提供快速的查找、添加和删除操作。哈希表通常是一个数组,数组的每个元素是一个指向键值对结构的指针。
  • 哈希冲突解决:当不同的键通过哈希函数映射到同一个位置时,redis使用链表法来解决冲突。如果一个位置有多个键值对,它们会形成一个链表。
  • rehash:随着键值对数量的增加或减少,为了维持哈希表的性能,redis会进行rehash操作,即重新计算所有键的哈希值,并将它们重新分布到新的哈希表中。
  • 渐进式rehash:为了避免rehash操作带来的性能问题,redis使用渐进式rehash。它将rehash操作分散到对字典的每个添加、删除、查找和更新操作中,从而避免了一次性rehash可能导致的长时间延迟。
  • 缓存作用:由于字典的高效访问特性,redis可以快速读写数据,这使得redis非常适合作为缓存系统使用。在字典中存储的数据可以直接从内存中访问,大大减少了数据读取的时间。
  • 持久化:虽然字典是内存中的数据结构,但redis支持将字典中的数据持久化到硬盘上,以保证在系统故障时数据不会丢失。
  • 类型特定字典:redis支持多种数据类型,如字符串、列表、集合、哈希、有序集合等,每种数据类型在内部都可能使用到字典结构来存储元数据或数据本身。

redis的字典缓存是支撑其高性能的一个关键因素,它使得redis能够以极快的速度处理大量的数据。

项目目录

代码实践

entity层

package com.wyl.redis.entity;
import com.baomidou.mybatisplus.annotation.idtype;
import com.baomidou.mybatisplus.annotation.tablefield;
import com.baomidou.mybatisplus.annotation.tableid;
import com.baomidou.mybatisplus.annotation.tablename;
import com.baomidou.mybatisplus.extension.activerecord.model;
import lombok.data;
import javax.persistence.*;
import java.io.serializable;
import java.time.localdatetime;
import java.util.date;
/**
 * @description 
 * @author wuyilong
 * @date 2024-07-03
 */
@data
@tablename("full_city")
@entity
@table(name="full_city")
public class fullcity extends model<fullcity> {
    private static final long serialversionuid = 1l;
    /**
     * 主键id
     */
    @tableid(value = "id", type = idtype.auto)
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    /**
     * 名称
     */
    @tablefield("name")
    private string name;
    /**
     * 行政编码
     */
    @tablefield("code")
    private string code;
    /**
     * 全名称
     */
    @tablefield("full_name")
    private string fullname;
    /**
     * 级别,1省,2市,3区,4街道
     */
    @tablefield("level")
    private integer level;
    /**
     * 创建时间
     */
    @tablefield("create_time")
    private date createtime;
    /**
     * 中心点
     */
    @tablefield("center")
    private string center;
    /**
     * 是否被撤销,0否,1是
     */
    @tablefield("is_revoke")
    private integer isrevoke;
    /**
     * 父级编码
     */
    private string parentcode;
    @override
    public serializable pkval() {
        return this.id;
    }
}

service层

package com.wyl.redis.service.impl;
import cn.hutool.core.lang.tree.tree;
import cn.hutool.core.lang.tree.treeutil;
import cn.hutool.core.map.maputil;
import com.wyl.redis.bean.dictionarybean;
import com.wyl.redis.constant.dictionaryconst;
import com.wyl.redis.entity.fullcity;
import com.wyl.redis.service.dictionaryoperate;
import com.wyl.redis.service.fullcityservice;
import com.wyl.redis.vo.fullcityvo;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.service;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import java.util.stream.collectors;
/**
 * @description
 * @author wuyilong
 * @date 2024/7/3 17:36
 */
@slf4j
@service
public class fullcityoperate implements dictionaryoperate {
    @autowired
    private fullcityservice fullcityservice;
    @autowired
    private redistemplate redistemplate;
    @override
    public list list(string key) {
        if(!redistemplate.haskey(key)) {
            list<fullcity> list = fullcityservice.list();
            list<dictionarybean> dictionarybeans = list.stream().map(m -> {
                dictionarybean dictionarybean = new dictionarybean();
                dictionarybean.setcode(m.getcode());
                dictionarybean.setname(m.getname());
                dictionarybean.setlevel(m.getlevel());
                dictionarybean.setparentcode(m.getparentcode());
                return dictionarybean;
            }).collect(collectors.tolist());
            redistemplate.opsforvalue().set(key,dictionarybeans);
            return dictionarybeans;
        }
        list<dictionarybean> list = (list<dictionarybean>)redistemplate.opsforvalue().get(key);
        return list;
    }
    @override
    public list<tree<string>> tree(string key) {
        if(!redistemplate.haskey(key)) {
            list<fullcity> list = fullcityservice.list();
            list<tree<string>> build = treeutil.build(list, "0", (t1, t2) -> {
                t2.setid(t1.getcode());
                t2.setname(t1.getname());
                t2.setparentid(t1.getparentcode());
            });
            redistemplate.opsforvalue().set(key,build);
            return build;
        }
        list<tree<string>> trees = (list<tree<string>>)redistemplate.opsforvalue().get(key);
        return trees;
    }
    @override
    public string codenamemap(string key, string code) {
        if(!redistemplate.opsforhash().haskey(key,code)) {
            fullcityvo fullcityvo = fullcityservice.getbycode(code);
            if(fullcityvo != null) {
                redistemplate.opsforhash().putifabsent(key,fullcityvo.getcode(),fullcityvo.getname());
                return fullcityvo.getname();
            }
            return null;
        }
        string name = (string)redistemplate.opsforhash().get(key, code);
        return name;
    }
    @override
    public string namecodemap(string key, string name) {
        if(!redistemplate.opsforhash().haskey(key,name)) {
            fullcityvo fullcityvo = fullcityservice.getbyfullname(name);
            if(fullcityvo != null) {
                redistemplate.opsforhash().putifabsent(key,fullcityvo.getfullname(),fullcityvo.getcode());
                return fullcityvo.getcode();
            }
            return null;
        }
        string code = (string)redistemplate.opsforhash().get(key, name);
        return code;
    }
    @override
    public string supporttype() {
        return dictionaryconst.full_city;
    }
}
package com.wyl.redis.service.impl;
import cn.hutool.core.lang.tree.tree;
import com.wyl.redis.constant.dictionaryconst;
import com.wyl.redis.exception.businessexception;
import com.wyl.redis.service.dictionaryoperate;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.beansexception;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.applicationcontext;
import org.springframework.context.applicationcontextaware;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.component;
import java.util.*;
/**
 * @description
 * @author wuyilong
 * @date 2024/7/3 17:23
 */
@slf4j
@component
public class dictionaryservice implements applicationcontextaware {
    private map<string,dictionaryoperate>  dictionarymaps = new hashmap<>();
    @autowired
    private redistemplate redistemplate;
    public dictionaryoperate builddictionaryoperate(string key) {
        dictionaryoperate dictionaryoperate = dictionarymaps.get(key);
        if(dictionaryoperate == null) {
            throw new businessexception("字典的key不存在");
        }
        return dictionaryoperate;
    }
    public list list(string key) {
        string listkey = dictionaryconst.dic+key+dictionaryconst.list;
        if(key.contains(":")) {
            string[] split = key.split(":");
            key = split[0];
            listkey = dictionaryconst.dic+key+dictionaryconst.list+":"+split[1];
        }
        list list = builddictionaryoperate(key).list(listkey);
        return list;
    }
    public list<tree<string>> tree(string key) {
        string listkey = dictionaryconst.dic+key+dictionaryconst.tree;
        if(key.contains(":")) {
            string[] split = key.split(":");
            key = split[0];
            listkey = dictionaryconst.dic+key+dictionaryconst.tree+":"+split[1];
        }
        list<tree<string>> tree =builddictionaryoperate(key).tree(listkey);
        return tree;
    }
    public string codenamemap(string key, string code) {
        string name = builddictionaryoperate(key).codenamemap(dictionaryconst.dic+key+":codenamemap", code);
        return name;
    }
    public string namecodemap(string key, string name) {
        string code = builddictionaryoperate(key).namecodemap(dictionaryconst.dic+key+":namecodemap", name);
        return code;
    }
    public void refresh() {
        set keys = redistemplate.keys("dic*");
        keys.foreach(v->{
            redistemplate.delete(v);
        });
    }
    @override
    public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
        map<string, dictionaryoperate> dictionaryoperatemap = applicationcontext.getbeansoftype(dictionaryoperate.class);
        dictionaryoperatemap.foreach((k,v)->{
            dictionarymaps.put(v.supporttype(),v);
        });
    }
}

controller层

package com.wyl.redis.controller;
import com.wyl.common.bean.responsedata;
import com.wyl.redis.service.impl.dictionaryservice;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
/**
 *
 * @description
 * @author wuyilong
 * @date 2024/7/8 10:21
 */
@api(tags = "字典api")
@restcontroller
@requestmapping(value = "dictionary")
public class dictionarycontroller {
    @autowired
    private dictionaryservice dictionaryservice;
    @apioperation(value = "字典刷新")
    @getmapping(value = "refresh")
    public responsedata refresh() {
        dictionaryservice.refresh();
        return responsedata.success();
    }
    @apioperation(value = "字典列表")
    @getmapping(value = "list")
    public responsedata list(string key) {
        return responsedata.successinstance(dictionaryservice.list(key));
    }
    @apioperation(value = "字典树")
    @getmapping(value = "tree")
    public responsedata tree(string key) {
        return responsedata.successinstance(dictionaryservice.tree(key));
    }
    @apioperation(value = "根据code获取名称")
    @getmapping(value = "codenamemap")
    public responsedata codenamemap(string key, string code) {
        return responsedata.successinstance(dictionaryservice.codenamemap(key,code));
    }
    @apioperation(value = "根据名称获取code")
    @getmapping(value = "namecodemap")
    public responsedata namecodemap(string key, string name) {
        return responsedata.successinstance(dictionaryservice.namecodemap(key, name));
    }
}

测试

根据code获取名称

字典列表

字典树

字典在redis客户端的存储

项目说明

只需要配置好本地的数据库,连接上自己本地的redis,启动项目,就会自动初始化数据库脚本到本地数据库。

package com.wyl.redis.config;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.datasourceproperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.dynamicdatasourceproperties;
import com.baomidou.dynamic.datasource.support.scriptrunner;
import com.baomidou.dynamic.datasource.toolkit.dynamicdatasourcecontextholder;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.applicationarguments;
import org.springframework.boot.applicationrunner;
import org.springframework.boot.autoconfigure.condition.conditionalonproperty;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.boot.jdbc.datasourcebuilder;
import org.springframework.stereotype.component;
import javax.sql.datasource;
import java.util.map;
/**
 * @description 公共初始化配置
 * @author wuyilong
 * @date 2024/7/8 9:38
 */
@slf4j
@conditionalonproperty(prefix = "init",value = "enabled",havingvalue = "true")
@component
public class initconfig implements applicationrunner {
    @autowired
    private dynamicdatasourceproperties dynamicdatasourceproperties;
    @override
    public void run(applicationarguments args) throws exception {
        log.info("****************初始化数据库脚本开始*************");
        map<string, datasourceproperty> datasource = dynamicdatasourceproperties.getdatasource();
        datasourceproperty master = datasource.get("master");
        datasource build = datasourcebuilder
                .create()
                .url(master.geturl())
                .driverclassname(master.getdriverclassname())
                .password(master.getpassword())
                .type(master.gettype())
                .username(master.getusername())
                .build();
        scriptrunner scriptrunner = new scriptrunner(true, ";");
        scriptrunner.runscript(build,"classpath:/db/**");
        log.info("****************初始化数据库脚本结束*************");
    }
}

在配置文件那里配置,设置init.enabled=true

init:
  enabled: false

项目地址

github

到此这篇关于springboot集成redis之字典缓存的文章就介绍到这了,更多相关springboot集成redis内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com