redis的使用

定义:============================================

        Redis 是一个内存中的数据结构存储系统,可以用作数据库、缓存和消息代理。它支持多种数据结构,如字符串(strings)、散列(hashes)、列表(lists)、集合(sets)、有序集合(sorted sets)等。Redis 的全称是 Remote Dictionary Server

springboot中使用redis缓存数据库热点信息:=============

1.下载安装redis:

Releases · microsoftarchive/redis · GitHub

2.引入redis起步依赖:

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

3.配置redis连接信息:

#application.yaml

  spring: 
     redis:
        host: localhost 
        port: 6379
        password: "123456" #未设置密码不用配置
        database: 2 #选择redis的库(可选)

4.配置redis键值的序列化器(非必须):

怎么理解:首先,使用默认的序列化器存取数据完全没问题,这个要理解。

默认序列化器是将所有的数据转换为二进制数据存入redis,这就意味着你使用redis控制台无法查看原本的数据,开发起来不方便。比如你存入了字符串“我好帅”,然后在redis控制台中查看可能就是这样"\xac\xed\x00\x05t\x00\x0b",使用虽然没问题但是不方便。

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

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

        // 设置 key 的序列化器为 StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());

        // 设置 value 的序列化器为 GenericJackson2JsonRedisSerializer
        //GenericJackson2JsonRedisSerializer可以处理各种类型的数据(对象、字符串、数字等)
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        return template;
    }
}

 插一嘴:spring data redis中操作各类型数据的api

public class SpringDateRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate(){
        System.out.println(redisTemplate);
        //操作字符串类型的数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //操作哈希类型的数据
        HashOperations hashOperations = redisTemplate.opsForHash();
        //操作列表类型的数据
        ListOperations listOperations = redisTemplate.opsForList();
        //操作集合类型的数据
        SetOperations setOperations = redisTemplate.opsForSet();
        //操作有序集合类型的数据
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
    }
}

5-1.使用redisTemplate的api存取字符串类型数据示例(较麻烦看看就好):

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void test() {

        // 存储字符串
        redisTemplate.opsForValue().set("stringKey", "stringValue");

        // 存储对象
        User user = new User("John", 30);
        redisTemplate.opsForValue().set("userKey", user);

        // 从 Redis 中读取数据
        String stringValue = (String) redisTemplate.opsForValue().get("stringKey");
        User retrievedUser = (User) redisTemplate.opsForValue().get("userKey");

        // 打印读取的数据
        System.out.println("Retrieved string: " + stringValue);
        System.out.println("Retrieved user: " + retrievedUser);
    }
}

5-2.使用注解自动管理缓存:

  • @CachePut:用于将方法返回值放入缓存,即使该键已经存在。
  • @Cacheable:用于从缓存中读取数据,如果缓存中没有数据,则执行方法体并将结果缓存。
  • @CacheEvict:用于从缓存中移除指定的键。

1.使用注解还需要再引入一项依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.启动类上添加@EnableCaching注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching //开启缓存支持
public class RedisExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedisExampleApplication.class, args);
    }
}
3.使用:
@Cacheable(value = "users", key = "#key")
public User getUser(String key) {
    //如果缓存中有值不会执行这个方法
    //如果缓存中没有值会自动将查询的数据存入缓存
    return fetchUserFromDataSource(key);
}

//上面是使用注解的方式
//分割线================================================================================
//他们俩实现的功能完全一样================================================================
//下面是使用redisTemplate提供的api方式


public User getUser(String key) {
    // 从缓存中获取数据
    User cachedUser = (User) redisTemplate.opsForValue().get("users::" + key);
    if (cachedUser != null) {
        return cachedUser; // 如果缓存中有数据,则直接返回
    }

    // 如果缓存没有数据从数据库中获取数据
    User user = fetchUserFromDataSource(key);

    // 将数据存入缓存
    redisTemplate.opsForValue().set("users::" + key, user);
    return user;
}

  • 17
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值