数据库
首页 > 数据库> > Spring整合Redis步骤

Spring整合Redis步骤

作者:互联网

引入依赖

可通过maven Repository查找到redis的坐标
https://mvnrepository.com/

#### 复制坐标
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.4.4</version>
</dependency>

配置redis

在配置文件application.properties中配置

# 选择哪一个数据库,redis一共16个数据库
spring.redis.database=11
# 设置地址
spring.redis.host=localhost
# 设置端口
spring.redis.port=6379

编写配置类,构造RedisTemplatere

通过redis的自动配置类可以看到自动配置的RedisTemplat是如下:

@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

可以看到RedisTemplat的key和value都是Object,不方便后面的使用,因此为redis写一个配置类,将RedisTemplat的key修改为String类型,自定义的配置类如下

@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;
    }

}

测试

新建一个测试类,即可测试redis

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)   //将该类作为配置类
public class redisTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testStrings(){
        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));
    }}

标签:Spring,redis,redisKey,RedisTemplate,template,步骤,Redis,public,redisTemplate
来源: https://blog.csdn.net/qq_38941890/article/details/115641394