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

Spring MVC使用Lettuce框架连接Redis

程序员文章站 2022-05-01 08:05:44
...

Maven

pom.xml

<!--redis-->
<!--spring支持-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>
<!--连接框架-->
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>5.1.4.RELEASE</version>
</dependency>
<!--连接池-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.6.0</version>
</dependency>

使用注解方式添加Bean

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import java.time.Duration;

@Configuration
@EnableWebMvc
public class RedisConnectionFactory {

    /**
     * Redis 连接配置
     * @return
     */
    @Bean(name = "stringRedisTemplate")
    public StringRedisTemplate init() {
        GenericObjectPoolConfig poolConfig;//连接池
        LettucePoolingClientConfiguration poolingClientConfiguration;//lettuce连接池配置
        RedisStandaloneConfiguration standaloneConfiguration;//spring redis 配置
        LettuceConnectionFactory lettuceConnectionFactory;//lettuce 连接工厂
        StringRedisTemplate stringRedisTemplate;//redis 操作类
        // 连接池
        poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(100);
        poolConfig.setMaxTotal(100);
        poolConfig.setMaxWaitMillis(Duration.ofMinutes(1).toMillis());
        // 连接客户端配置
        poolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(poolConfig)
                .build();
        // 连接配置
        standaloneConfiguration = new RedisStandaloneConfiguration("127.0.0.1", 6379);//端口和地址
        standaloneConfiguration.setPassword(RedisPassword.none());// 这里的redis没有设置密码
        standaloneConfiguration.setDatabase(0);//默认选第一个数据库
        // 连接工厂
        lettuceConnectionFactory = new LettuceConnectionFactory(standaloneConfiguration, poolingClientConfiguration);
        // 记得应用设置
        lettuceConnectionFactory.afterPropertiesSet();
        // 已经默认了序列化为UTF-8的字符串序列化
        stringRedisTemplate = new StringRedisTemplate(lettuceConnectionFactory);
        return stringRedisTemplate;
    }
}

最后不要忘了在spring的配置文件里面配置包的扫描路径

<context:component-scan base-package="com.example"/>