redisTemplate.opsForValue()
redisTemplate.opsForHash()
redisTemplate.opsForList()
redisTemplate.opsForSet()
redisTemplate.opsForZSet()

1.引入依赖

        <dependency&gt;
			<groupId&gt;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 配置类:

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());
        // 设置hashkey序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hashvalue的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());

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

3.访问 Redis

编写测试代码

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

原文地址:https://blog.csdn.net/m0_72161237/article/details/134650060

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_5689.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注