自动装配-自定义starter

将redis生成分布式唯一id的功能封装成starter供其他模块使用

1 编写业务类

package com.yangkun.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;


public class RedisCache {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //redis生成唯一id
    public Long nextId(String keyWord){
        Long BEGIN_TIMESTAMP = LocalDateTime.of(2022,1,1,0,0,0).toEpochSecond(ZoneOffset.UTC);
        //时间戳
        LocalDateTime now = LocalDateTime.now();
        Long newSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = newSecond-BEGIN_TIMESTAMP;
        //生成序列号
        //获取当前日期,精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyy:yy:dd"));
        //自增长,redis根据key生成一个唯一id,keyWord根据业务传不同的值,比如订单模块的id就传 order,用户模块的id就传user,date是每天不同的,
        //因为long是64位,返回值long的低32位是redis自增位,如果每天都用同一个key的话,超过2的32次方后会生成重复的id,date每天变化,只要当天不超过2的32次方个id就不会重复
        long count = stringRedisTemplate.opsForValue().increment("icr:"+keyWord+":"+date);
        //返回格式: 最高位符号位(0),31位时间戳,32位redis自增位
        return timeStamp << 32 |count;
    }
}

2 编写配置类

package com.yangkun.redis;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import javax.annotation.Resource;
 
@Configuration //表示该类为配置类
// @EnableConfigurationProperties({xxx.class}) 有的类需要从配置文件获取值,可以开启这个注解,比如有的类用@ConfigurationProperties/@value从配置文件取值
public class AutoConfig {  @Bean public RedisCache getRedisCache(){ return new RedisCache(); } }

3 在resources\META-INF\spring.factories里配置 AutoConfig 配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.yangkun.redis.AutoConfig

4 执行maven-install命令在maven仓库里生成jar包

5 其他模块相关操作

 5.1 pom文件里加入依赖,再使用@Autowired/@Resource注入RedisCache类

5.2 注意: 需要在application.yml里配置redis,如果自定义starter里有需要从配置文件里取值的,需要在配置文件里定义好

posted @ 2023-04-23 16:00  杨吃羊  阅读(33)  评论(0)    收藏  举报