9.Spring 整合 Redis

  • 引入依赖:spring-boot-starter-data-redis
  • 配置 Redis:配置数据库参数、编写配置类,构造 RedisTemplate
  • 访问 Redis:
redisTemplate.opsForValue()
redisTemplate.opsForHash()
redisTemplate.opsForList()
redisTemplate.opsForSet()
redisTemplate.opsForZSet()

1.引入依赖

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

2.配置 Redis

2.1 配置数据库参数

# RedisProperties
spring.redis.database=2
spring.redis.host=localhost
spring.redis.port=6379

2.2 编写配置类,构造 RedisTemplate

在 config 配置包下新建 RedisConfig 配置类:

  •  添加注解 @Configuration
  • 添加 @Bean
  • 返回 RedisTemplate
  • 访问数据库需要创建连接(而连接是由连接工厂创建),注入连接工厂,在方法上声明连接工厂(Spring 容器自动把 Bean 注入)
  • 实例化 Bean
  • 把工厂设置给 Bean:具备了访问数据库能力
  • 配置序列化方式,最终把数据存入 redis 中:设置key的序列化方式(字符串)、设置value的序列化方式(JSON)、设置hash的key的序列化方式、设置hash的value的序列化方式
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hash的value的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());

        //触发参数
        template.afterPropertiesSet();
        return template;
    }
}

3.访问 Redis

编写测试类代码:

  • 注入 RedisTemplate
  • 访问字符串
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = DemoApplication.class)
public class RedisTests {

    @Autowired
    private RedisTemplate redisTemplate;

    //String 访问方式
    @Test
    public void testStrings() {
        //声明 key
        String redisKey = "test:count";

        redisTemplate.opsForValue().set(redisKey, 1);

        System.out.println(redisTemplate.opsForValue().get(redisKey));
        System.out.println(redisTemplate.opsForValue().increment(redisKey));
        System.out.println(redisTemplate.opsForValue().decrement(redisKey));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗小温

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值