池化 redis

springboot 池化 redis?

在Spring Boot中使用Redisson时,可以通过配置文件来设置连接池参数。Redisson的连接池在其配置中称为连接(Connection)配置。以下是如何配置Redisson连接池以及一些建议:

  1. 添加Redisson依赖:首先,在您的Spring Boot项目中的pom.xml(如果使用Maven)或build.gradle(如果使用Gradle)文件中添加Redisson依赖。

  2. 创建Redisson配置文件:在src/main/resources目录下创建一个名为redisson.yaml的配置文件。在此文件中,您可以配置Redisson的连接池参数。

  3. 配置连接池参数:在redisson.yaml文件中,可以设置以下连接池参数:

  • connectionMinimumIdleSize:设置最小空闲连接数。建议根据您的应用需求设置合适的值,以确保有足够的空闲连接可用。
  • connectionPoolSize:设置连接池的大小。这个值取决于您的并发需求和服务器性能。建议设置为可处理的最大并发请求数的两倍左右。
  • idleConnectionTimeout:设置空闲连接超时时间(毫秒)。当连接处于空闲状态超过此时间后,将被关闭。
  • connectTimeout:设置连接超时时间(毫秒)。当建立新连接时,如果超过此时间仍无法建立连接,则视为超时。
  • timeout:设置命令执行超时时间(毫秒)。当执行Redis命令时,如果超过此时间仍无法完成,则视为超时。

以下是一个示例配置:

singleServerConfig:
  idleConnectionTimeout: 10000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  address: "redis://127.0.0.1:6379"
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 50
  connectionMinimumIdleSize: 10
  connectionPoolSize: 64
  database: 0
  dnsMonitoringInterval: 5000
  1. 在Spring Boot应用中加载Redisson配置:在您的Spring Boot配置类中,添加一个方法以加载redisson.yaml文件并创建一个Redisson客户端Bean:
@Configuration
public class RedissonConfig {

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws IOException {
        Config config = Config.fromYAML(new ClassPathResource("redisson.yaml").getInputStream());
        return Redisson.create(config);
    }
}

通过以上步骤,您可以在Spring Boot中配置Redisson连接池。请注意,您可能需要根据实际应用场景和服务器性能调整连接池参数,以获得最佳性能。在生产环境中,建议您不断监控和调整参数,以确保Redis性能始终处于最佳状态。

配置了连接池之后, springboot中如何使用redis呢?

在Spring Boot中配置了Redisson连接池后,您可以在需要使用Redis的地方注入RedissonClient。以下是如何在Spring Boot应用中使用Redisson连接池:

  1. 注入RedissonClient:在您需要使用Redis的类中,使用@Autowired注解注入RedissonClient。例如:
@Service
public class YourService {

    @Autowired
    private RedissonClient redissonClient;

    // ...
}
  1. 执行Redis操作:通过RedissonClient,您可以执行各种Redis操作。Redisson提供了丰富的API,支持Redis的各种数据结构和命令。以下是一些示例:

字符串(String)操作

public void setString(String key, String value) {
    RBucket<String> bucket = redissonClient.getBucket(key);
    bucket.set(value);
}

public String getString(String key) {
    RBucket<String> bucket = redissonClient.getBucket(key);
    return bucket.get();
}

通过RedissonClient的getBucket(key)方法获取RBucket对象,然后调用set(value)方法,就可以将键值对存储到Redis。这里的代码示例使用了Redisson的高级API,它将底层Redis操作进行了封装,使得在Java代码中操作Redis更加简便和直观。

列表(List)操作

public void addToList(String key, String value) {
    RList<String> list = redissonClient.getList(key);
    list.add(value);
}

public List<String> getList(String key) {
    RList<String> list = redissonClient.getList(key);
    return list.readAll();
}

集合(Set)操作

public void addToSet(String key, String value) {
    RSet<String> set = redissonClient.getSet(key);
    set.add(value);
}

public Set<String> getSet(String key) {
    RSet<String> set = redissonClient.getSet(key);
    return set.readAll();
}

哈希(Hash)操作

public void putToHash(String key, String hashKey, String value) {
    RMap<String, String> map = redissonClient.getMap(key);
    map.put(hashKey, value);
}

public String getFromHash(String key, String hashKey) {
    RMap<String, String> map = redissonClient.getMap(key);
    return map.get(hashKey);
}
  1. 关闭RedissonClient:在Spring Boot应用关闭时,需要关闭RedissonClient以释放资源。由于我们在创建RedissonClient Bean时已经添加了destroyMethod = "shutdown",因此Spring Boot会自动关闭RedissonClient。

通过以上步骤,您可以在Spring Boot应用中使用Redisson连接池来执行Redis操作。请注意,根据您的实际需求,可以使用更多的Redisson API来操作Redis的其他数据结构和功能。详细的API文档和示例可以在Redisson官方文档中找到:Home · redisson/redisson Wiki · GitHub

SpringBoot整合Redis

1:导入相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xxy</groupId>
    <artifactId>redis-java</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis-java</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.16</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2:配置application.yml

server:
  port: 8000


spring:
  redis:
    host: localhost
    port: 6379
    timeout: 5000
    password: 123456
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0

3:Redis配置

package com.xxy.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 兴跃
 * Redis配置类
 */
@Configuration
public class RedisConfig {

    @Bean

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);

        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

4:Redis工具类

package com.xxy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 兴跃
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    /*************************************key的一系列操作*******************************************/
    /**
     * 直接写入缓存
     */
    public boolean set(final String key, Object value) {
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 写入并设置过期时间
     *
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean set(final String key, Object value, long expireTime, TimeUnit timeUnit) {

        try {
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 指定key到期时间
     *
     * @param key
     * @param time
     * @param timeUnit
     * @return
     */
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除key的过期时间,key将要持久保持
     *
     * @param key
     * @return
     */
    public boolean persist(String key) {
        return redisTemplate.persist(key);
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0或-1代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void remove(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 判断缓存中是否存在该key对应的value
     *
     * @param key
     * @return
     */
    public boolean hasKey(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 普通根据key获取
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 序列化key
     *
     * @param key
     * @return
     */
    public byte[] dump(String key) {
        return redisTemplate.dump(key);
    }

    /**
     * 从当前数据库中随机返回一个 key
     *
     * @return
     */
    public String randomKey() {
        return redisTemplate.randomKey().toString();
    }

    /**
     * 修改 key 的名称
     *
     * @param oldKey
     * @param newKey
     */
    public void rename(String oldKey, String newKey) {
        redisTemplate.rename(oldKey, newKey);
    }

    /**
     * 仅当 newkey 不存在时,将 oldKey 改名为 newkey
     *
     * @param oldKey
     * @param newKey
     * @return
     */
    public Boolean renameIfAbsent(String oldKey, String newKey) {
        return redisTemplate.renameIfAbsent(oldKey, newKey);
    }

    /**
     * 返回 key 所储存的值的类型
     *
     * @param key
     * @return
     */
    public DataType type(String key) {
        return redisTemplate.type(key);
    }

    /**
     * 获取所保存的字符的长度
     *
     * @param key
     * @return
     */
    public Long size(String key) {
        return redisTemplate.opsForValue().size(key);
    }

    /**
     * 批量添加
     *
     * @param maps
     */
    public void multiSet(Map<String, String> maps) {
        redisTemplate.opsForValue().multiSet(maps);
    }

    /**
     * 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在
     *
     * @param maps
     * @return 之前已经存在返回false, 不存在返回true
     */
    public boolean multiSetIfAbsent(Map<String, String> maps) {
        return redisTemplate.opsForValue().multiSetIfAbsent(maps);
    }

    /**
     * 增加(自增长), 负数则为自减
     *
     * @param key
     * @return
     */
    public Long incrBy(String key, long increment) {
        return redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * 追加到末尾
     *
     * @param key
     * @param value
     * @return
     */
    public Integer append(String key, String value) {
        return redisTemplate.opsForValue().append(key, value);
    }

    /*************************************hash的一系列操作*******************************************/
    /**
     * 往hash中保存数据
     *
     * @param key
     * @param hKey
     * @param value
     */
    public void hPut(final String key, final String hKey, final Object value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 往hash表中存多个数据
     *
     * @param key
     * @param maps
     */
    public void hPutAll(String key, Map<String, String> maps) {
        redisTemplate.opsForHash().putAll(key, maps);
    }

    /**
     * 获取hash表中的数据
     *
     * @param key
     * @param hKey
     * @return
     */
    public Object hGet(final String key, final String hKey) {
        return redisTemplate.opsForHash().get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public List<Object> hMultiGet(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }
    /**
     * 获取所有哈希表中的字段
     *
     * @param key
     * @return
     */
    public Set<Object> hKeys(String key) {
        return redisTemplate.opsForHash().keys(key);
    }
    /**
     * 获取哈希表中字段的数量
     *
     * @param key
     * @return
     */
    public Long hSize(String key) {
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 获取哈希表中所有值
     *
     * @param key
     * @return
     */
    public List<Object> hValues(String key) {
        return redisTemplate.opsForHash().values(key);
    }
    /*************************************set的一系列操作*******************************************/
    /**
     * 往Set中存入数据
     *
     * @param key    Redis键
     * @param values 值
     * @return 存入的个数
     */
    public long sSet(final String key, final Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 删除Set中的数据
     *
     * @param key    Redis键
     * @param values 值
     * @return 移除的个数
     */
    public long setDel(final String key, final Object... values) {
        Long count = redisTemplate.opsForSet().remove(key, values);
        return count == null ? 0 : count;
    }
    /**
     * 获取集合的大小
     *
     * @param key
     * @return
     */
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }
    /**
     * 判断集合是否包含value
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }
    /**
     * 获取两个集合的交集
     *
     * @param key
     * @param otherKey
     * @return
     */
    public Set<String> sIntersect(String key, String otherKey) {
        return redisTemplate.opsForSet().intersect(key, otherKey);
    }

    /**
     * 获取key集合与多个集合的交集
     *
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sIntersect(String key, Collection<String> otherKeys) {
        return redisTemplate.opsForSet().intersect(key, otherKeys);
    }
    /**
     * 获取两个集合的并集
     *
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sUnion(String key, String otherKeys) {
        return redisTemplate.opsForSet().union(key, otherKeys);
    }

    /**
     * 获取key集合与多个集合的并集
     *
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sUnion(String key, Collection<String> otherKeys) {
        return redisTemplate.opsForSet().union(key, otherKeys);
    }
    /**
     * 获取集合所有元素
     *
     * @param key
     * @return
     */
    public Set<String> setMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }
    /*************************************list的一系列操作*******************************************/

    /**
     * 往List中存入数据
     *
     * @param key Redis键
     * @param value 数据
     * @return 存入的个数
     */
    public  long listPush(final String key, final Object value) {
        Long count = redisTemplate.opsForList().rightPush(key, value);
        return count == null ? 0 : count;
    }

    /**
     * 往List中存入多个数据
     *
     * @param key Redis键
     * @param values 多个数据
     * @return 存入的个数
     */
    public  long listPushAll(final String key, final Collection<Object> values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 往List中存入多个数据
     *
     * @param key Redis键
     * @param values 多个数据
     * @return 存入的个数
     */
    public  long listPushAll(final String key, final Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        return count == null ? 0 : count;
    }

    /**
     * 从List中获取begin到end之间的元素
     *
     * @param key Redis键
     * @param start 开始位置
     * @param end 结束位置(start=0,end=-1表示获取全部元素)
     * @return List对象
     */
    public  List<Object> listGet(final String key, final int start, final int end) {
        return redisTemplate.opsForList().range(key, start, end);
    }
}

5:测试

@SpringBootTest
class RedisJavaApplicationTests {
 @Autowired
    private RedisUtils redisUtils;

    @Test
    void contextLoads(){
        //直接保存
        redisUtils.set("token", list);
        //保存到Redis并且设置过期时间
        redisUtils.set("司", "夏", 30, TimeUnit.SECONDS);
    }
}

 

posted @ 2024-07-01 10:24  CharyGao  阅读(6)  评论(0编辑  收藏  举报