Giter Club home page Giter Club logo

redis-spring-boot's Introduction

redis-spring-boot

一个轻量级用于简化redis操作,基于spring boot的starter组件,并且提供了基于redis的分布式锁以及动态消息发布/订阅的功能

基本配置

1、先把项目clone到本地
git clone [email protected]:terminux/redis-spring-boot.git
2、进入到项目根目录下执行
mvn -pl '!redis-spring-boot-samples' -DskipTests clean install
3、给项目添加依赖
<dependency>
    <groupId>com.ugrong.framework</groupId>
    <artifactId>redis-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>
4、在项目中配置一下redis
spring:
  redis:
    password: your_password
    host: localhost
    port: 6379

开始使用

1、假如我们需要序列化一个学生类到redis,需要实现序列化接口,例如:
@Getter
@Setter
@ToString
public class Student implements Serializable {

    private Long id;

    private String name;
}
2、实现 IRedisCacheType 接口,并且重写 [getValue] 方法,例如用枚举实现:
public enum EnumStudentCacheType implements IRedisCacheType {

    /**
     * 学生信息缓存
     */
    STUDENT_CACHE("STUDENT");

    private final String value;

    EnumStudentCacheType(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return this.value;
    }
}

这样可以方便在key很多的情况下方便我们管理key,同时根据不同的业务场景统一key的规范

3、创建 StudentRedisRepository,并且继承 AbstractSimpleRedisRepository ,重写它的 [getCacheType] 方法,例如:
@Component
public class StudentRedisRepository extends AbstractSimpleRedisRepository<Student> {

    @Override
    public IRedisCacheType getCacheType() {
        return EnumStudentCacheType.STUDENT_CACHE;
    }
}
这样就很方便地可以在 service 中使用:
@Autowired
private StudentRedisRepository studentRedisRepository;
来对 redis 中的 Student 进行操作了
4、简单的字符串操作可以直接使用 IStringRedisRepository :
@Autowired
private IStringRedisRepository stringRedisRepository;
5、为了支持不同数据结构的存储,除了 AbstractSimpleRedisRepositoryIStringRedisRepository
还提供了 AbstractHashRedisRepositoryAbstractListRedisRepository ,可以自行查看和使用

分布式锁

1、项目中还支持了redis分布式锁,可以在 IRedisLockRepository 中查看提供的方法和详细注释
2、在项目中注入 IRedisLockRepository
@Autowired
private IRedisLockRepository redisLockRepository;
3、执行加锁
伪代码如下:
AtomicBoolean isLock = new AtomicBoolean(Boolean.FALSE);
try {
    isLock.set(redisLockRepository.tryLock(...));
    if (isLock.get()) {
        //获取到锁
        //do something
    }
} catch (InterruptedException e) {
    e.printStackTrace();
} finally {
    //进行解锁
    if (isLock.get()) {
        redisLockRepository.unlock(...);
    }
}
4、示例
4.1、实现 IRedisLockType 接口,并且重写 [getValue] 方法,例如用枚举实现:
public enum EnumStudentLockType implements IRedisLockType {

    STUDENT_LOCK("STUDENT_LOCK");

    private final String value;

    EnumStudentLockType(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}
4.2、对id为 123456 的学生进行加锁
IRedisLockType lockType = EnumStudentLockType.STUDENT_LOCK;
String lockField = "123456";
AtomicBoolean isLock = new AtomicBoolean(Boolean.FALSE);
try {
    isLock.set(redisLockRepository.tryLock(lockType, lockField, 20, 20, TimeUnit.SECONDS));
    if (isLock.get()) {
       //获取到锁
       //do something
    }
} catch (InterruptedException e) {
    e.printStackTrace();
} finally {
    //进行解锁
    if (isLock.get()) {
        redisLockRepository.unlock(lockType, lockField);
    }
}
5、提供了 @RedisLock 注解来支持aop加锁

动态消息发布及订阅

消息发布者
  • 1、实现 IRedisTopicType 接口,并且重写 [getValue] 方法,用来作为发布的消息主题类型,支持主题表达式

  • 2、在项目中注入 IRedisChannelRepository 即可使用

IRedisTopicType 示例:

public enum EnumStudentTopicType implements IRedisTopicType {

    STUDENT_TOPIC("/student/test_topic");

    private final String value;

    EnumStudentTopicType(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}

发送消息示例:

 redisChannelRepository.publish(EnumStudentTopicType.STUDENT_TOPIC, student);
消息订阅者

示例:

@Component
@RedisHandler(topic = "/student/test_topic")
@Slf4j
public class StudentMessageHandler implements IRedisMessageHandler<Student> {

    @Override
    public void handle(Student student, String topic) {
        log.info("Handle redis message.topic=[{}], received=[{}]", topic, student);
    }
}

注:相关单元测试可以在 SamplesApplicationTests 类中查看

redis-spring-boot's People

Contributors

terminux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.