autofill,spring aop redis

发布于:2025-07-21 ⋅ 阅读:(16) ⋅ 点赞:(0)

公共字段自动填充(AutoFill + Spring AOP)

1 注解定义

@Target(ElementType.METHOD)           // 仅可标注在方法上 :contentReference[oaicite:0]{index=0}  
@Retention(RetentionPolicy.RUNTIME)   // 运行期可反射读取 :contentReference[oaicite:1]{index=1}  
public @interface AutoFill {
    OperationType value();            // 必填枚举:INSERT 或 UPDATE
}

该注解为数据库写操作打上“插入 / 更新”标签,供切面在执行前判定应填充的字段集合。

2 切面核心逻辑

@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
public void autoFillPointCut(){}

@Before("autoFillPointCut()")
public void autoFill(JoinPoint jp){
    // ① 读取操作类型
    OperationType op = ((MethodSignature) jp.getSignature())
                       .getMethod().getAnnotation(AutoFill.class).value();
    // ② 解析实体参数
    Object entity = jp.getArgs()[0];
    LocalDateTime now = LocalDateTime.now();
    Long uid = BaseContext.getCurrentId();

    // ③ 通过反射调用 setter
    if (op == OperationType.INSERT) { …setCreateTime/UpdateTime/User… }
    else if (op == OperationType.UPDATE) { …setUpdateTime/User… }
}

Spring AOP 在方法进入前执行该前置通知,完成四/两项公共字段的统一写入,提高一致性并消除重复代码 (Home)。


阿里云 OSS 文件上传

1 属性与 YAML

# application-dev.yml
sky:
  alioss:
    endpoint: ...
    access-key-id: ...
    access-key-secret: ...
    bucket-name: ...
# application.yml 通过占位符复用
sky:
  alioss:
    endpoint: ${sky.alioss.endpoint}

不同 profile 通过占位符共享一份主配置,便于多环境切换

2 工具类与配置

@Data @AllArgsConstructor
public class AliOssUtil {                         // 调用官方 SDK putObject
    public String upload(byte[] bytes, String obj){
        OSS client = new OSSClientBuilder().build(endpoint,id,secret);
        client.putObject(bucketName, obj, new ByteArrayInputStream(bytes));  // :contentReference[oaicite:3]{index=3}
        client.shutdown();
        return "https://" + bucketName + "." + endpoint + "/" + obj;
    }
}

@Configuration
public class OssConfiguration {
    @Bean @ConditionalOnMissingBean            // 若容器已有同类型 Bean 则跳过 :contentReference[oaicite:4]{index=4}
    public AliOssUtil aliOssUtil(AliOssProperties p){
        return new AliOssUtil(p.getEndpoint(), p.getAccessKeyId(),
                              p.getAccessKeySecret(), p.getBucketName());
    }
}

该配置类保证 AliOssUtil 只有一份单例,被 Spring 注入到 CommonController 统一调用。


Redis 与 RedisTemplate

1 依赖与配置

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
  redis:
    host: ...
    port: ...
    password: ...
    database: 0

2 模板 Bean

@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory f){
    RedisTemplate<String,Object> t = new RedisTemplate<>();
    t.setConnectionFactory(f);
    t.setKeySerializer(new StringRedisSerializer());   // 人类可读 :contentReference[oaicite:5]{index=5}
    return t;
}

redisTemplate.opsForValue().get(key)set(key,val) 等 API 即可完成 KV 操作,在高频读取场景显著降低数据库压力。


Spring Cache 简述

引入 spring-boot-starter-cache 后,启用 @EnableCaching,即可使用
@Cacheable(读缓存)、@CacheEvict(清除)、@CachePut(更新)等注解在 Service 层无侵入地添加缓存策略 (Home, Baeldung)。Spring Cache 只是抽象;底层实现可选 Redis、Caffeine 等。


Apache HttpClient 简要示例

CloseableHttpClient hc = HttpClients.createDefault();
HttpGet get = new HttpGet("https://example.com");
CloseableHttpResponse resp = hc.execute(get);
String body = EntityUtils.toString(resp.getEntity());

Spring Boot 可在配置类中注入 CloseableHttpClient 并在 Service 调用外部 REST API (GeeksforGeeks)。


小结

  • AutoFill 注解 + AOP:在 Mapper 层统一填写 create_timeupdate_user 等公共字段,减少样板逻辑。

  • AliOssUtil:封装官方 SDK putObject,通过 OssConfiguration 以条件 Bean 方式注入,确保单例安全。

  • RedisTemplate:自定义序列化器后键值可读,配合 Spring Cache 注解获得透明缓存能力。

  • 配置文件application-dev.yml 存放环境敏感配置;application.yml 使用占位符引用,便于多环境管理。
    通过上述整理,代码层次清晰,配置集中,便于维护与扩展。