redis使用

redis集群搭建可参考:redis集群搭建-CSDN博客

一、简述

Redis(Remote Dictionary Server)是一个开源的、基于内存的高性能键值对存储系统,通常用作数据库、缓存和消息代理。它支持多种数据结构,包括字符串、哈希、列表、集合和有序集合

1.1 Redis相关问题

1、Redis是单线程模式,但速度很快,原因是:

1.Redis的数据存储在内存中,读写速度极快

2.Redis的单线程避免了多线程的上下文切换

3.采用I/O复用技术,可以同时处理多个请求

4.采用高效的数据结构,例如:哈希表

2、Redis序列化:

Redis的序列化作用是将对象转换为字节流以便存储或传输,在Redis中,所有数据都是以字节的形式存储的,因此当我们需要将对象存储到Redis时,需要先将其序列化为字节数组;

3、Redis序列化的形式:

‌StringRedisSerializer‌:将String类型的数据序列化为字节数组,适用于String或数值类型数据‌。

‌GenericJackson2JsonRedisSerializer‌:使用Jackson库将对象序列化为JSON字符串,这种方式适用于复杂的对象数据,因为它可以保留对象的结构和属性‌。

‌JdkSerializationRedisSerializer‌:使用Java内置的序列化机制,将对象转换为字节流。这是Redis的默认序列化方式

二、redis的使用

2.1 redis做数据库

1、添加依赖

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、配置连接

bash 复制代码
# application.yml
spring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword

3、创建配置类

java 复制代码
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        
        // 使用GenericJackson2JsonRedisSerializer来序列化和反序列化redis的value值
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        // 设置hash key 和 value 序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        template.afterPropertiesSet();
        return template;
    }
}

4、服务层和redis交互

java 复制代码
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void setKey(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getKey(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    //hash
    public void setHash(String key, Map<String, Object> values) {
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        hashOperations.putAll(key, values);
    }

    public Map<Object, Object> getHash(String key) {
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        return hashOperations.entries(key);
    }
    //参数是hash表的键名和字段名
    public Object getHashField(String key, String field) {
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        return hashOperations.get(key, field);
    }


    //list
    public void leftPush(String key, String value) {
        ListOperations<String, String> listOperations = stringRedisTemplate.opsForList();
        listOperations.leftPush(key, value);
    }
    //key是键 start开始索引,从0开始 end结束索引,如果设为-1,表示获取列表中的所有元素
    public List<String> getRange(String key, long start, long end) {
        ListOperations<String, String> listOperations = stringRedisTemplate.opsForList();
        return listOperations.range(key, start, end);
    }


    //Zset
    public void addZSetMember(String key, String value, double score) {
        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();
        zSetOperations.add(key, value, score);
    }

    public Set<String> getZSetMembers(String key) {
        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();
        return zSetOperations.range(key, 0, -1);
    }
}

2.2 redis做缓存

1、添加完依赖后,在启动类添加注解@EnableCaching

java 复制代码
@SpringBootApplication
@EnableCaching
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

2、创建缓存的配置类

java 复制代码
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 设置key和value的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
               .entryTtl(Duration.ofMinutes(10)) // 设置缓存过期时间
               .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置key序列化方式
               .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); // 设置value序列化方式
        return RedisCacheManager.builder(factory).cacheDefaults(config).build();
    }
}

3、定义mapper和xml文件中的sql

java 复制代码
public interface UserMapper {
    User getUserById(Long id);
}

//有多个参数时
public interface UserMapper {
   User getUserByIdAndName(@Param("id") Long id, @Param("name") String name);
}
XML 复制代码
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
    <select id="getUserById" resultType="com.example.entity.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

<!-- 多个参数时 -->
<select id="getUserByIdAndName" resultType="User">
   SELECT * FROM users WHERE id = #{id} AND name = #{name}
</select>

4、service层添加缓存注解

java 复制代码
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Cacheable(value = "userCache", key = "#id")
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    //多个参数时
    @Cacheable(value = "users", key = "#id + '_' + #name")
    public User getUserByIdAndName(Long id, String name) {
        return userMapper.getUserByIdAndName(id, name);
    }
}

@Cacheable注解指定了缓存的名称为userCache,并使用用户的ID作为缓存的键。如果缓存中已经存在对应键的数据,则直接从缓存中获取,否则执行方法内的逻辑,并将结果存入缓存

2.3 redis做分布式锁

1、添加依赖

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、获取和释放锁的类

java 复制代码
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String LOCK_PREFIX = "lock:";
    private static final long DEFAULT_EXPIRE_TIME = 30; // 锁默认过期时间,单位:秒

    /**
     * 尝试获取锁
     *
     * @param key       锁的键
     * @param expireTime 锁的过期时间,单位:秒
     * @return 是否获取锁成功
     */
    public boolean tryLock(String key, long expireTime) {
        String lockKey = LOCK_PREFIX + key;
        // 使用SETNX命令尝试获取锁
        //lockKey是键,"locked"是值,expireTime是过期时间,TimeUnit.SECONDS指定了过期时间的单位为秒
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "locked", expireTime, TimeUnit.SECONDS);
        return success != null && success;
    }

    /**
     * 释放锁
     *
     * @param key 锁的键
     */
    public void unlock(String key) {
        String lockKey = LOCK_PREFIX + key;
        // 删除锁键来释放锁
        stringRedisTemplate.delete(lockKey);
    }
}

3、使用

java 复制代码
@Service
public class YourService {

    @Autowired
    private RedisLock redisLock;

    public void someMethod() {
        //key值,可以是业务id,保证唯一性
        String lockKey = "someResource";
        boolean lockAcquired = redisLock.tryLock(lockKey, 30); // 尝试获取锁,过期时间30秒
        if (lockAcquired) {
            try {
                // 执行需要同步的代码
            } finally {
                // 确保在代码执行完毕后释放锁
                redisLock.unlock(lockKey);
            }
        } else {
            // 处理获取锁失败的情况,例如重试或返回错误消息
        }
    }
}
相关推荐
冼紫菜26 分钟前
【Spring Boot 多模块项目】@MapperScan失效、MapperScannerConfigurer 报错终极解决方案
java·开发语言·mybatis
还听珊瑚海吗1 小时前
基于SpringBoot的抽奖系统测试报告
java·spring boot·后端
练习本1 小时前
Android系统架构模式分析
android·java·架构·系统架构
心灵宝贝3 小时前
IDEA 安装 SpotBugs 插件超简单教程
java·macos·intellij-idea
幼稚诠释青春3 小时前
Java学习笔记(对象)
java·开发语言
小羊学伽瓦4 小时前
【Java基础】——JVM
java·jvm
老任与码4 小时前
Spring AI(2)—— 发送消息的API
java·人工智能·spring ai
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧4 小时前
MyBatis快速入门——实操
java·spring boot·spring·intellij-idea·mybatis·intellij idea
csdn_freak_dd4 小时前
查看单元测试覆盖率
java·单元测试
爱吃烤鸡翅的酸菜鱼4 小时前
【SpringMVC】详解cookie,session及实战
java·http·java-ee·intellij-idea