Skip to content

dict不会自动刷新val #8377

@zingyangcn

Description

@zingyangcn
版本号: 3.7.1
问题描述:

使用@dict(dictTable ="sys_position",dicText = "name",dicCode = "id")类似的表的字典的时候,如果修改了数据库的值缓存没有得到同步更新

错误截图:
建议:

声明一个刷新字典的切面,以下是mock的代码

package org.jeecg.common.aspect.annotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RefreshDictCache {
    String table();
    String text();
    String code();
    String valueField() default "id"; // 变更的主键字段名,默认id
    String dataSource() default "";
}
package org.jeecg.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.jeecg.common.aspect.annotation.RefreshDictCache;
import org.jeecg.common.util.DictCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class DictCacheRefreshAspect {

    @Autowired
    private DictCacheUtil dictCacheUtil;

    @AfterReturning(pointcut = "@annotation(refreshDictCache)", returning = "result")
    public void afterEdit(JoinPoint joinPoint, RefreshDictCache refreshDictCache, Object result) {
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            Object entity = args[0]; // 假设第一个参数就是实体
            try {
                // 通过反射获取主键值
                Method getter = entity.getClass().getMethod(
                    "get" + Character.toUpperCase(refreshDictCache.valueField().charAt(0)) + refreshDictCache.valueField().substring(1)
                );
                Object value = getter.invoke(entity);
                dictCacheUtil.refreshDictCache(
                    refreshDictCache.table(),
                    refreshDictCache.text(),
                    refreshDictCache.code(),
                    value != null ? value.toString() : null,
                    refreshDictCache.dataSource()
                );
                log.info("自动刷新字典缓存: {} {} {} {}", refreshDictCache.table(), refreshDictCache.text(), refreshDictCache.code(), value);
            } catch (Exception e) {
                log.warn("自动刷新字典缓存失败", e);
            }
        }
    }
}

友情提示:

  • 未按格式要求发帖、描述过于简单的,会被直接删掉;
  • 描述问题请图文并茂,方便我们理解并快速定位问题;
  • 如果使用的不是master,请说明你使用的分支;

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions