SpringBoot+redis时事务和SessionCallback的使用和抉择

4 篇文章 0 订阅

首先从使用springboot+redis碰到的一个问题说起。在前几篇文章中介绍了用SpringBoot+redis构建了一个个人博客。在刚开始远行的时候发现发了几个请求操作了几次redis之后,后面的就被阻塞了,请求一直在等待返回,我们重现一下问题。建议使用后面提到的SessionCallback。
[注意] 该问题只会出现在springboot 2.0之前的版本;2.0之后springboot连接Redis改成了lettuce,并重新实现,问题已经不存在

打开Template的事务支持

POM 配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.springboot</groupId>
    <artifactId>redis-tx-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBoot redis TX demo</name>
    <description>Demo project for Spring Boot with Redis transaction</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Redis configuration (EnbaleTransactionSupport设为true):

 

@Configuration
public class RedisConfiguration {

    @Bean
    public StringRedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setEnableTransactionSupport(true); //打开事务支持
        return template;
    }
}

Controller就是简单的set一个key到redis:

 

@RestController
public class DemoController {
    
    private StringRedisTemplate template;
    
    public DemoController(StringRedisTemplate template) {
        this.template = template;
    }
    
    @GetMapping("/put")
    public String redisSet() {
        int i = (int)(Math.random() * 100);
        template.opsForValue().set("key"+i, "value"+i, 300, TimeUnit.SECONDS);
        return "success "+"key"+i;
    }

}

启动后,我们使用RestClient发送请求http://localhost:8080/put,发送8次之后就会发现没有返回了。这个时候我们查看redis的链接数,发现已经超过8个,springboot对于jedis连接池默认的最大活跃连接数是8,所以看出来是连接池被耗光了。

 

127.0.0.1:6379> info clients
# Clients
connected_clients:9
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0
127.0.0.1:6379>

还有查看程序的日志可以发现,RedisConnectionUtils只有Opening RedisConnection而没有close。

 

2018-08-11 11:00:48.889 [DEBUG][http-nio-8080-exec-8]:o.s.data.redis.core.RedisConnectionUtils [doGetConnection:126] Opening RedisConnection
2018-08-11 11:00:50.169 [DEBUG][http-nio-8080-exec-8]:o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor [writeWithMessageConverters:249] Written [success key39] as "text/plain" using [org.springframework.http.converter.StringHttpMessageConverter@766a49c7]
2018-08-11 11:00:50.170 [DEBUG][http-nio-8080-exec-8]:org.springframework.web.servlet.DispatcherServlet [processDispatchResult:1044] Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-08-11 11:00:50.170 [DEBUG][http-nio-8080-exec-8]:org.springframework.web.servlet.DispatcherServlet [processRequest:1000] Successfully completed request
2018-08-11 11:00:50.170 [DEBUG][http-nio-8080-exec-8]:o.s.boot.web.filter.OrderedRequestContextFilter [doFilterInternal:104] Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@c03b2d8
2018-08-11 11:00:53.854 [DEBUG][http-nio-8080-exec-9]:o.s.boot.web.filter.OrderedRequestContextFilter [initContextHolders:114] Bound request context to thread: org.apache.catalina.connector.RequestFacade@c03b2d8
2018-08-11 11:00:53.856 [DEBUG][http-nio-8080-exec-9]:org.springframework.web.servlet.DispatcherServlet [doService:865] DispatcherServlet with name 'dispatcherServlet' processing GET request for [/put]
2018-08-11 11:00:53.857 [DEBUG][http-nio-8080-exec-9]:o.s.w.s.m.m.a.RequestMappingHandlerMapping [getHandlerInternal:310] Looking up handler method for path /put
2018-08-11 11:00:53.857 [DEBUG][http-nio-8080-exec-9]:o.s.w.s.m.m.a.RequestMappingHandlerMapping [getHandlerInternal:317] Returning handler method [public java.lang.String com.github.springboot.demo.DemoController.redisSet()]
2018-08-11 11:00:53.858 [DEBUG][http-nio-8080-exec-9]:o.s.b.factory.support.DefaultListableBeanFactory [doGetBean:251] Returning cached instance of singleton bean 'demoController'
2018-08-11 11:00:53.858 [DEBUG][http-nio-8080-exec-9]:org.springframework.web.servlet.DispatcherServlet [doDispatch:951] Last-Modified value for [/put] is: -1
2018-08-11 11:00:53.861 [DEBUG][http-nio-8080-exec-9]:o.s.data.redis.core.RedisConnectionUtils [doGetConnection:126] Opening RedisConnection

关闭template的事务支持

接下来我们修改一下RedisConfiguration的配置,不启用事务管理,

 

@Bean
    public StringRedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
//      template.setEnableTransactionSupport(true);   //禁用事务支持
        return template;
    }

重新测试一下,发现是正常的,redis的client链接数一直保持在2。程序日志里的也可以看到Redis Connection关闭的日志。

 

2018-08-11 15:55:19.975 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [doGetConnection:126] Opening RedisConnection
2018-08-11 15:55:20.029 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [releaseConnection:210] Closing Redis Connection
2018-08-11 15:55:20.056 [DEBUG][http-nio-8080-exec-1]:o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor [writeWithMessageConverters:249] Written [success key72] as "text/plain" using [org.springframework.http.converter.StringHttpMessageConverter@51ab1ee3]

也就是说,如果我们把事务的支持打开,spring在每次操作之后是不会主动关闭连接的。我们去RedisTemplate的源码中找下原因。

 

public ValueOperations<K, V> opsForValue() {
        if (valueOps == null) {
            valueOps = new DefaultValueOperations<K, V>(this);
        }
        return valueOps;
}

可以发现template.opsForValue().set()操作最终是调用的DefaultValueOperations中的set()方法,继续跟进去最终调用的RedisTemplate中的execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline)方法。

 

public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
        Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
        Assert.notNull(action, "Callback object must not be null");

        RedisConnectionFactory factory = getConnectionFactory();
        RedisConnection conn = null;
        try {

            if (enableTransactionSupport) {
                // only bind resources in case of potential transaction synchronization
                conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
            } else {
                conn = RedisConnectionUtils.getConnection(factory);
            }

            boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);

            RedisConnection connToUse = preProcessConnection(conn, existingConnection);

            boolean pipelineStatus = connToUse.isPipelined();
            if (pipeline && !pipelineStatus) {
                connToUse.openPipeline();
            }

            RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
            T result = action.doInRedis(connToExpose);

            // close pipeline
            if (pipeline && !pipelineStatus) {
                connToUse.closePipeline();
            }

            // TODO: any other connection processing?
            return postProcessResult(result, connToUse, existingConnection);
        } finally {
            RedisConnectionUtils.releaseConnection(conn, factory);
        }
    }

可以看到获取连接的操作也针对打开事务支持的template有特殊的处理逻辑。这里我们先跳过,先看看最终肯定会走到的RedisConnectionUtils.releaseConnection(conn, factory)这一步。

 

/**
     * Closes the given connection, created via the given factory if not managed externally (i.e. not bound to the
     * thread).
     * 
     * @param conn the Redis connection to close
     * @param factory the Redis factory that the connection was created with
     */
    public static void releaseConnection(RedisConnection conn, RedisConnectionFactory factory) {

        if (conn == null) {
            return;
        }

        RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager.getResource(factory);

        if (connHolder != null && connHolder.isTransactionSyncronisationActive()) {
            if (log.isDebugEnabled()) {
                log.debug("Redis Connection will be closed when transaction finished.");
            }
            return;
        }

        // release transactional/read-only and non-transactional/non-bound connections.
        // transactional connections for read-only transactions get no synchronizer registered
        if (isConnectionTransactional(conn, factory)
                && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            unbindConnection(factory);
        } else if (!isConnectionTransactional(conn, factory)) {
            if (log.isDebugEnabled()) {
                log.debug("Closing Redis Connection");
            }
            conn.close();
        }
    }

可以看到针对打开事务支持的template,只是解绑了连接,根本没有做close的操作。关于什么是解绑,其实这个方法的注释中已经说的比较清楚了,对于开启了事务的Template,由于已经绑定了线程中连接,所以这里是不会关闭的,只是做了解绑的操作。
到这里原因就很清楚了,就是只要template开启了事务支持,spring就认为只要使用这个template就会包含在事务当中,因为一个事务中的操作必须在同一个连接中完成,所以在每次get/set之后,template是不会关闭链接的,因为它不知道事务有没有结束。

使用@Transanctional注解支持Redis事务

既然RedisTemlatesetEnableTransactionSupport会造成连接不关闭,那怎么样才能正常关闭呢?我们将事务支持开关和@Transanctional结合起来用看看会怎么样。
spring中要使用@Transanctional首先要配transactionManager,但是spring没有专门针对Redis的事务管理器实现,而是所有调用RedisTemplate的方法最终都会调用到RedisConnctionUtils这个类的方法上面,在这个类里面会判断是不是进入到事务里面,也就是说Redis的事务管理的功能是由RedisConnctionUtils内部实现的。
根据官方文档,我只想用Redis事务,也必须把JDBC捎上。当然反过来讲,不依赖数据的项目确实不多,貌似这么实现影响也不大。下面我们先根据官方文档配置一下看看效果。
首先修改POM配置,添加两个依赖。如果项目里本来已经使用了数据库,那这一步就不需要了。

 

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
</dependency>

然后修改RedisConfiguration

 

@Bean
    public StringRedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setEnableTransactionSupport(true);//打开事务支持
        return template;
    }

    //配置事务管理器
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) throws SQLException {
        return new DataSourceTransactionManager(dataSource);
    }

我们新建一个RedisService,将原来的数据操作移到service里面。同时将Service方法加上@Transactional注解。

 

@Service
public class RedisService {
    
    private StringRedisTemplate template;
    
    public RedisService(StringRedisTemplate template) {
        this.template = template;
    }

    @Transactional
    public String put() {
        int i = (int)(Math.random() * 100);
        template.opsForValue().set("key"+i, "value"+i, 300, TimeUnit.SECONDS);
        return "success "+"key"+i;
    }
}
//-----------------------------------------------------------
//controller里面加一个新的方法,调用Service
@GetMapping("/puttx")
public String redisTxSet() {
    return redisService.put();
}

完成这些工作之后,再往http://localhost:8080/puttx发送请求,无论点多少次,Redis的连接数始终维持在1个不变。在看程序的输出日志里面我们也发现了,事务结束后连接被正常释放。因为使用了JDBC的事务管理器,所以还顺便做了一次数据库事务的开启和提交。还有一点值得注意的是,跟数据库一样,使用注解来做事务管理,spring也会主动管理redis事务的提交和回滚,也就是在之前发送一条MULTI命令,成功后发送EXEC,失败后发送DISCARD。

 

2018-08-11 20:57:04.990 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [doGetConnection:126] Opening RedisConnection
2018-08-11 20:57:04.990 [DEBUG][http-nio-8080-exec-1]:o.springframework.aop.framework.JdkDynamicAopProxy [getProxy:118] Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [org.springframework.data.redis.connection.jedis.JedisConnection@20f2be3c]
2018-08-11 20:57:04.990 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [intercept:337] Invoke 'multi' on bound conneciton
2018-08-11 20:57:04.991 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [intercept:337] Invoke 'isPipelined' on bound conneciton
2018-08-11 20:57:04.991 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [intercept:337] Invoke 'setEx' on bound conneciton
2018-08-11 20:57:04.991 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [releaseConnection:198] Redis Connection will be closed when transaction finished.
2018-08-11 20:57:04.991 [DEBUG][http-nio-8080-exec-1]:o.s.jdbc.datasource.DataSourceTransactionManager [processCommit:759] Initiating transaction commit
2018-08-11 20:57:04.991 [DEBUG][http-nio-8080-exec-1]:o.s.jdbc.datasource.DataSourceTransactionManager [doCommit:310] Committing JDBC transaction on Connection [ProxyConnection[PooledConnection[conn9: url=jdbc:h2:mem:testdb user=SA]]]
2018-08-11 20:57:04.992 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [intercept:337] Invoke 'exec' on bound conneciton
2018-08-11 20:57:04.992 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [afterCompletion:306] Closing bound connection after transaction completed with 0
2018-08-11 20:57:04.992 [DEBUG][http-nio-8080-exec-1]:o.s.data.redis.core.RedisConnectionUtils [intercept:337] Invoke 'close' on bound conneciton
2018-08-11 20:57:04.993 [DEBUG][http-nio-8080-exec-1]:o.s.jdbc.datasource.DataSourceTransactionManager [doCleanupAfterCompletion:368] Releasing JDBC Connection [ProxyConnection[PooledConnection[conn9: url=jdbc:h2:mem:testdb user=SA]]] after transaction
2018-08-11 20:57:04.993 [DEBUG][http-nio-8080-exec-1]:o.springframework.jdbc.datasource.DataSourceUtils [doReleaseConnection:327] Returning JDBC Connection to DataSource

总结

在spring中要使用Redis注解式事务,首先要设置RedisTemplateenableTransactionSupport属性为true,然后配置一个jdbc的事务管理器。
这里有一点非常重要,一旦这样配置,所有使用这个template的redis操作都必须走注解式事务,要不然会导致连接一直占用,不关闭。

建议

  • 升级到springboot 2.0以上版本,如果因为项目原因无法升级看下面的建议
  • 如果使用Redis事务的场景不多,完全可以自己管理,不需要使用spring的注解式事务。如下面这样使用:

 

List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
  public List<Object> execute(RedisOperations operations) throws DataAccessException {
    operations.multi();
    operations.opsForSet().add("key", "value1");
    // This will contain the results of all ops in the transaction
    return operations.exec();
  }
});
  • 如果一定要使用spring提供的注解式事务,建议初始化两个RedisTemplate Bean,分别设置enableTransactionSupport属性为true和false。针对需要事务和不需要事务的操作使用不同的template。
  • 从个人角度,我不建议使用redis事务,因为redis对于事务的支持并不是关系型数据库那样满足ACID。Redis事务只能保证ACID中的隔离性和一致性,无法保证原子性和持久性。而我们使用事务最重要的一个理由就是原子性,这一点无法保证,事务的意义就去掉一大半了。所以事务的场景可以尝试通过业务代码来实现。

------- 对于Redis集群时:

项目中在其中一个数据库的update方法里,这个方法上开启了事务@Transactional,导致里面的删除redis key操作也加入了事务。
上线后出现报错:


这个报错明确指出,集群模式的redis不支持事务。集群不支持事务的原因可参考此文:Is there any Redis client (Java prefered) which supports transactions on Redis cluster?
基于此次问题,总结出本文内容

1、Spring中的事务

所有数据访问技术都有事务机制,这些技术提供了API来开启事务、提交事务完成数据操作, 或者在发生错误的时候回滚数据。
Spring采用统一的机制来处理不同的数据访问技术的事务, Spring的事务提供一个PlatformTransactionManager的接口,不同的数据访问技术使用不同的接口实现。

数据访问技术实现
JDBCDataSourceTransactionManager
JPAJPATransactionManager
HibernateHibernateTransactionManager
JDOJDOTransactionManager
分布式事务JtaTransactionManager

在SpringBoot中开启事务非常简单,只需要在方法或类上使用注解@Transactional即可。
Spring官方文档中还要求使用@EnableTransactionManagement 开启事务,但SpringBoot通过自动配置已经帮我们做了,所以SpringBoot中不用写该注解
这里重点讲下@Transactional注解的几个常用属性

  • propagation

事务的传播机制,主要有以下几种,默认是REQUIRED

  1. REQUIRED - 方法A调用时候没有事务新建一个事务,在方法A中调用方法B,将使用相同的事务,如果方法B发生异常需要回滚,整个事务回滚。

  2. REQUIRES_NEW - 方法A调用方法B时,无论是否存在事务都开启一个新事务,这样B方法异常不会导致A的数据回滚。

  3. NESTED - 和REQUIRES_NEW类似,但是只支持JDBC,不支持JPA或Hibernate

  4. SUPPORTS - 方法调用时有事务就用事务,没事务就不用事务

  5. NOT_SUPPORTED - 强制方法不在事务中执行,若有事务,在方法调用到结束阶段先挂起事务。

  6. NEVER - 强制不能有事务,若有事务就抛出异常

  7. MANDATORY - 强制必须有事务,如果没有事务就抛出异常

  • rollbackFor

指定哪些异常可以导致事务回滚,默认是Throwable的子类

  • noRollbackFor

执行哪些异常不可用引起事务回滚,默认是Throwable的子类

2、@Transactional事务失效的情况

  1. 只对public方法生效。默认的protected和private方法上写上@Transactional不会报错,但该方法上的事务不生效,官方原文:Method visibility and @Transactional
  2. 默认情况(只写@Transactional不填写rollbackFor参数)下此注解会对unchecked异常进行回滚,对checked异常不回滚;
  3. 类内部未开启事务的方法调用开启事务的方法
    前两条很好理解,针对3,引用丁雪丰的《Spring全家桶》视频中的解释:

Spring的声明式事务本质上是通过AOP来增强了类的功能
Spring的AOP本质上就是为类做了一个代理

看似在调用自己写的类,实际用的是增强后的代理类

下图描述了方法被事务代理时的流程,来源:Spring AOP

3、SpringBoot整合Redis事务实践

下面我们搭建一个最简单的SpringBoot整合redis的工程用代码来验证redis事务

  • SpringBoot整合Redis

SpringBoot整合redis使用的是spring-boot-starter-data-redis,redis事务依赖于jdbc的事务管理,所以还需要引入jdbc
pom相关引入:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
  • 开启Redis事务

编写redis配置类,开启redis事务,配置事务管理

@Configuration
public class RedisConfig {
    @Bean
    public StringRedisTemplate StringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        /**
         * description 开启redis事务(仅支持单机,不支持cluster)
         **/
        template.setEnableTransactionSupport(true);
        return template;
    }

    /**
     * description 配置事务管理器
     **/
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
  • 代码验证

针对本文讨论,设计了四个验证方法,可自行验证

    /**
     * description 不带事务set
     * return java.lang.String
     * author 郑晓龙
     * createTime 2019/12/12 16:36
     **/
    @GetMapping("put")
    public void put(String key, String value) {
        redisService.put(key, value);
    }

    /**
     * description 带事务set
     * return java.lang.String
     * author 郑晓龙
     * createTime 2019/12/12 16:36
     **/
    @GetMapping("putWithTx")
    public void putWithTx(String key, String value) {
        redisService.putWithTx(key, value);
    }

    /**
     * description 调用带事务方法不生效的情况
     * return java.lang.String
     * author 郑晓龙
     * createTime 2019/12/12 16:36
     **/
    @GetMapping("invokeWithPutTx")
    public void invokeWithPutTx(String key, String value) {
        redisService.invokePutWithTx(key, value);
    }

    /**
     * description 调用带事务方法生效的情况
     * return java.lang.String
     * author 郑晓龙
     * createTime 2019/12/12 16:36
     **/
    @GetMapping("invokeWithPutTx2")
    public void invokeWithPutTx2(String key, String value) {
        redisService.invokePutWithTx2(key, value);
    }

4、总结:

  • redis事务只支持单机,不支持cluster
  • 需要开启事务时,只需要在对应的方法或类上使用@Transactional注解即可,SpringBoot自动开启了@EnableTransactionManagement
  • 需要注意事务不生效的几种情况
  • redis事务依赖于jdbc的事务管理

参考:https://www.jianshu.com/p/c9f5718e58f0

https://www.cnblogs.com/zhengxl5566/p/12028293.html

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于Spring的应用程序的框架,而Redis是一个开源的内存数据存储系统。结合使用Spring Boot和Redis可以实现高效的数据缓存和持久化。 在Spring Boot中使用Redis,首先需要在项目的pom.xml文件中添加Redis的依赖。然后,在application.properties或application.yml文件中配置Redis的连接信息,包括主机名、端口号、密码等。 接下来,可以通过使用Spring Data Redis来简化对Redis的操作。Spring Data Redis提供了一系列的注解和模板类,可以方便地进行数据的读取、写入和删除等操作。 以下是一个简单的示例,演示了如何在Spring Boot中使用Redis: 1. 添加依赖: 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息: 在application.properties或application.yml文件中添加以下配置: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建Redis操作类: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void delete(String key) { redisTemplate.delete(key); } } ``` 4. 使用Redis操作类: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private RedisUtil redisUtil; @GetMapping("/user/{id}") public User getUser(@PathVariable String id) { // 先从缓存中获取数据 User user = (User) redisUtil.get("user:" + id); if (user == null) { // 如果缓存中不存在,则从数据库中获取数据 user = userService.getUserById(id); // 将数据存入缓存 redisUtil.set("user:" + id, user); } return user; } } ``` 以上示例中,我们创建了一个RedisUtil类来封装对Redis的操作,然后在UserController中使用RedisUtil来实现对用户数据的缓存。当请求用户数据,先从缓存中获取,如果缓存中不存在,则从数据库中获取,并将数据存入缓存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值