SpringBoot集成Redis

本文介绍如何在Spring Boot项目中配置并使用Redis。通过pom.xml引入spring-boot-starter-data-redis依赖,设置Redis连接参数,并自定义RedisTemplate实现序列化配置。最终通过测试代码演示了基本的读写操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、环境
  • Redis-x64-3.2.100.zip
  • SpringBoot 1.5.10.RELEASE

Redis-x64-3.2.100.zip 下载地址:https://github.com/MicrosoftArchive/redis/releases

pom依赖:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>


redis:
  database: @redis.database@ # Database index used by the connection factory.
  host: @redis.host@ # Redis server host.
  password: @redis.password@ # Login password of the redis server.
  port: @redis.port@
  pool:
    max-active: 50 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
    max-idle: 50 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
    max-wait: 50 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
    min-idle: 0
  timeout: 1000



三.config


@Configuration
public class RedisConfiguration {

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

}

四.测试Test

@Autowired

private RedisTemplate<String, Object> redisTemplate;

// 存取对象

redisTemplate.opsForValue().set("user", new User(1, "张三"));

User user = (User) redisTemplate.opsForValue().get("user");

System.out.println(user);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值