欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Data Redis 详解及实战一文搞定

程序员文章站 2022-04-25 18:11:28
SDR Spring Data Redis的简称。 Spring Data Redis提供了从Spring应用程序轻松配置和访问Redis的功能。它提供了与商店互动的低级别和高级别抽象,使用户免受基础设施问题的困扰。 Spring Boot 实战 引用依赖 添加redis配置类 添加redis配置参 ......

sdr - spring data redis的简称。

spring data redis提供了从spring应用程序轻松配置和访问redis的功能。它提供了与商店互动的低级别和高级别抽象,使用户免受基础设施问题的困扰。

spring boot 实战

引用依赖

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
    <version>${spring-boot.version}</version>
</dependency>

添加redis配置类

@enablecaching
@configuration
public class redisconfig extends cachingconfigurersupport {

    @bean
    public keygenerator keygenerator() {
        return (object target, method method, object... params) -> {
            stringbuilder sb = new stringbuilder();
            sb.append(target.getclass().getname());
            sb.append(method.getname());
            for (object obj : params) {
                sb.append(obj.tostring());
            }
            return sb.tostring();
        };
    }

    @bean
    public cachemanager cachemanager(redistemplate redistemplate) {
        rediscachemanager cachemanager = new rediscachemanager(redistemplate);
        cachemanager.setdefaultexpiration(10000);
        return cachemanager;
    }

    @bean
    public redistemplate<string, string> redistemplate(redisconnectionfactory factory) {
        stringredistemplate template = new stringredistemplate(factory);
        template.setvalueserializer(getserializer(template));
        template.afterpropertiesset();
        return template;
    }

    private redisserializer getserializer(stringredistemplate template) {
        objectmapper om = new objectmapper();
        om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
        om.enabledefaulttyping(objectmapper.defaulttyping.non_final);

        jackson2jsonredisserializer serializer = new jackson2jsonredisserializer(object.class);
        serializer.setobjectmapper(om);

        return serializer;
    }

}

添加redis配置参数:

spring.redis:
  database: 0 # redis数据库索引(默认为0)
  host: 192.168.1.168
  port: 6379
  #password: 123456
  timeout: 0 # 连接超时时间(毫秒)
  pool: 
    max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
    max-idle: 8 # 连接池中的最大空闲连接
    max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
    min-idle: 0 # 连接池中的最小空闲连接

开始使用

@autowired
private redistemplate redistemplate;

...
redistemplate.opsforvalue().set("test", system.currenttimemillis());
...

通过 redistemplate 处理对象

大多数用户可能会使用redistemplate它的相应软件包org.springframework.data.redis.core-由于其丰富的功能集,模板实际上是redis模块的中心类。该模板提供了redis交互的高级抽象。虽然redisconnection提供接受和返回二进制值(byte数组)的低级别方法,但模板负责序列化和连接管理,使用户无需处理这些细节。

此外,该模板提供了操作视图,它提供丰富的,通用的接口,用于针对特定类型或某些键(通过keybound接口)进行操作,如下所述:

键类型操作:
接口 描述
geooperations redis的地理空间操作,如geoadd,georadius..
hashoperations redis散列类型操作
hyperloglogoperations redis的hyperloglog操作,如pfadd,pfcount..
listoperations redis列表操作
setoperations redis集合操作
valueoperations redis字符串操作
zsetoperations redis有序集合操作
键绑定操作:
接口 描述
boundgeooperations redis的地理空间操作
boundhashoperations redis散列类型键绑定操作
boundkeyoperations redis键绑定操作
boundlistoperations redis列表键绑定操作
boundsetoperations redis集合键绑定操作
boundvalueoperations redis字符串键绑定操作
boundzsetoperations redis有序集合键绑定操作
怎么使用?

spring boot实战redis章节配置完成后,使用spring直接注入即可。

public class example {

  @autowired
  private redistemplate<string, string> template;

  @resource(name="redistemplate")
  private listoperations<string, string> listops;

  public void addlink(string userid, url url) {
    listops.leftpush(userid, url.toexternalform());
  }
}

redistemplate是线程安全的,开箱即用,可以在多个实例中重复使用。

redistemplate和stringredistemplate区别?

org.springframework.data.redis.core.redistemplate

org.springframework.data.redis.core.stringredistemplate

1、stringredistemplate继承自redistemplate

2、stringredistemplate默认使用string序列化方式,redistemplate默认使用jdk自带的序列化方式。

3、两者数据不互通,只能各自管理各自处理过的数据。

推荐使用stringredistemplate。

直接与redis对话

直接底层的与redis对话,没有封装。默认配置只能一个数据库,如下,可以直接通过获取stringredisconnection来切换当前操作的数据库。

stringredistemplate.execute((rediscallback<boolean>) connection -> {
    stringredisconnection stringredisconnection = (stringredisconnection) connection;
    stringredisconnection.select(5);
    stringredisconnection.set("name", "zoe");
    return true;
});

序列化器

从spring data redis框架本身的角度看,存放到redis的数据只是字节,虽然redis本身支持各种类型,但大部分是指数据存储的方式,而不是它所代表的内容,由用户决定是否将字节转换为字符串或其他对象。

用户自定义类型和原始数据之间的转换由org.springframework.data.redis.serializer包中的序列化器进行处理。

这个包下面主要包含了两种类型的序列化器:

  • 基于redisserializer的双向串行器。
  • 元素的读写使用的rediselementreader和rediselementwriter。

它们的主要区别是,redisserializer序列化成byte[],而后者使用的是bytebuffer。

序列化器实现类

这里有几种开箱即用的实现,其中有两种在之前的文章已经涉及过。

实现 描述
stringredisserializer string/byte[]转换,速度快
jdkserializationredisserializer jdk自带序列化
oxmserializer xml序列化,占空间,速度慢
jackson2jsonredisserializer json序列化,需要定义javatype
genericjackson2jsonredisserializer json序列化,无需定义javatype

所以,如果只是简单的字符串类型,使用stringredisserializer就可以了,如果要有对象就使用json的序列化吧,可以很方便的组装成对象。

事务支持

spring data redis提供了对redis的事务支持,如:multi, exec, discard命令。

spring data redis提供了sessioncallback接口,在同一个连接中需要执行多个操作时使用,与使用redis事务时一样。

示例

@test
public void testtransaction() {
    list<object> txresults = (list<object>) stringredistemplate
            .execute(new sessioncallback<list<object>>() {
                public list<object> execute(redisoperations operations)
                        throws dataaccessexception {
                    operations.multi();
                    operations.opsforset().add("t1", "value1");
                    operations.opsforset().add("t2", "value2");
                    operations.opsforset().add("t3", "value3");
                    return operations.exec();
                }
            });
    txresults.foreach(e -> logger.info("txresults: " + e));
}

以上代码,是一个接受字符串值的模板,redistemplate会使用相应的序列化器,如果把value3换成非字符串333,那第3条会报错,前面两个也不会保存成功。

当然,exec方法也可以接受自定义的序列化器

list<object> exec(redisserializer<?> valueserializer);

@transactional注解支持

注解事务支持在默认情况下是禁用的,必须通过把redistemplate设置明确开启事务支持:setenabletransactionsupport(true),如果没有错误即成功,有错误就全部回滚。当前连接所有写操作都会进入操作队列,读操作会转移到一个新的连接。

示例配置

@configuration
public class redistxcontextconfiguration {
  @bean
  public stringredistemplate redistemplate() {
    stringredistemplate template = new stringredistemplate(redisconnectionfactory());
    // explicitly enable transaction support
    template.setenabletransactionsupport(true);
    return template;
  }

  @bean
  public platformtransactionmanager transactionmanager() throws sqlexception {
    return new datasourcetransactionmanager(datasource());
  }

  @bean
  public redisconnectionfactory redisconnectionfactory( // jedis || lettuce);

  @bean
  public datasource datasource() throws sqlexception { // ... }
}
使用约束
// 绑定到当前线程上的连接
template.opsforvalue().set("foo", "bar");

// 读操作不参与事务
connection template.keys("*");

// 当在事务中设置的值不可见时返回null
template.opsforvalue().get("foo");

关注下面的微信公众号,回复 “答案” 获取全套redis面试题及答案。