当前位置: 首页 > article >正文

spring boot 同一个redis 操作不同的库

1.下面是在Spring Boot中配置多个Redis数据库的几种方式:

1.1 配置如下
# application.yml
spring:
  redis:
    host: localhost
    port: 6379
    password: your_password
    # 连接池配置
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms
    timeout: 5000ms
    
    # 多个数据库配置
    database0:
      database: 0  # 默认库
    database1:
      database: 1  # 订单库
    database2:
      database: 2  # 用户库

2. Redis配置类

2.1代码如下
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig {

    @Bean
    @Primary
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory connectionFactory) {
        return createRedisTemplate(connectionFactory);
    }
    
    @Bean(name = "redisTemplate1")
    public RedisTemplate<String, Object> redisTemplate1(
            @Qualifier("redisConnectionFactory1") RedisConnectionFactory connectionFactory) {
        return createRedisTemplate(connectionFactory);
    }
    
    @Bean(name = "redisTemplate2")
    public RedisTemplate<String, Object> redisTemplate2(
            @Qualifier("redisConnectionFactory2") RedisConnectionFactory connectionFactory) {
        return createRedisTemplate(connectionFactory);
    }
    
    @Bean
    @Primary
    public RedisConnectionFactory redisConnectionFactory(
            @Value("${spring.redis.host}") String host,
            @Value("${spring.redis.port}") int port,
            @Value("${spring.redis.password}") String password,
            @Value("${spring.redis.database0.database}") int database) {
        return createConnectionFactory(host, port, password, database);
    }
    
    @Bean(name = "redisConnectionFactory1")
    public RedisConnectionFactory redisConnectionFactory1(
            @Value("${spring.redis.host}") String host,
            @Value("${spring.redis.port}") int port,
            @Value("${spring.redis.password}") String password,
            @Value("${spring.redis.database1.database}") int database) {
        return createConnectionFactory(host, port, password, database);
    }
    
    @Bean(name = "redisConnectionFactory2")
    public RedisConnectionFactory redisConnectionFactory2(
            @Value("${spring.redis.host}") String host,
            @Value("${spring.redis.port}") int port,
            @Value("${spring.redis.password}") String password,
            @Value("${spring.redis.database2.database}") int database) {
        return createConnectionFactory(host, port, password, database);
    }
    
    private RedisTemplate<String, Object> createRedisTemplate(
            RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // 配置序列化器
        Jackson2JsonRedisSerializer<Object> jsonSerializer = 
            new Jackson2JsonRedisSerializer<>(Object.class);
            
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
            ObjectMapper.DefaultTyping.NON_FINAL);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.registerModule(new JavaTimeModule());
        
        jsonSerializer.setObjectMapper(mapper);
        
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jsonSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jsonSerializer);
        
        template.afterPropertiesSet();
        return template;
    }
    
    private RedisConnectionFactory createConnectionFactory(
            String host, int port, String password, int database) {
        LettuceConnectionFactory factory = new LettuceConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setDatabase(database);
        
        // Lettuce连接池配置
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxIdle(8);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(-1);
        
        factory.afterPropertiesSet();
        return factory;
    }
}

3.Redis操作服务

3.1 代码如下
@Service
@Slf4j
public class RedisService {

    @Autowired
    @Qualifier("redisTemplate")  // 默认库
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    @Qualifier("redisTemplate1")  // 订单库
    private RedisTemplate<String, Object> redisTemplate1;
    
    @Autowired
    @Qualifier("redisTemplate2")  // 用户库
    private RedisTemplate<String, Object> redisTemplate2;
    
    /**
     * 默认库操作
     */
    public void setDefault(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("Redis默认库操作失败: key={}", key, e);
            throw new RuntimeException("Redis操作失败", e);
        }
    }
    
    /**
     * 订单库操作
     */
    public void setOrder(String key, Object value) {
        try {
            redisTemplate1.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("Redis订单库操作失败: key={}", key, e);
            throw new RuntimeException("Redis操作失败", e);
        }
    }
    
    /**
     * 用户库操作
     */
    public void setUser(String key, Object value) {
        try {
            redisTemplate2.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("Redis用户库操作失败: key={}", key, e);
            throw new RuntimeException("Redis操作失败", e);
        }
    }
    
    /**
     * 批量操作示例
     */
    public void batchOperation() {
        try {
            // 使用管道批量处理
            redisTemplate.executePipelined(new SessionCallback<Object>() {
                @Override
                public Object execute(RedisOperations operations) throws DataAccessException {
                    operations.opsForValue().set("key1", "value1");
                    operations.opsForValue().set("key2", "value2");
                    return null;
                }
            });
            
            redisTemplate1.executePipelined(new SessionCallback<Object>() {
                @Override
                public Object execute(RedisOperations operations) throws DataAccessException {
                    operations.opsForValue().set("order1", "value1");
                    operations.opsForValue().set("order2", "value2");
                    return null;
                }
            });
        } catch (Exception e) {
            log.error("Redis批量操作失败", e);
            throw new RuntimeException("Redis操作失败", e);
        }
    }
}

4. 使用示例

4.1代码如下
@RestController
@RequestMapping("/api/redis")
@Slf4j
public class RedisController {

    @Autowired
    private RedisService redisService;
    
    @PostMapping("/default")
    public ResponseEntity<?> setDefault(@RequestParam String key, 
                                      @RequestParam String value) {
        try {
            redisService.setDefault(key, value);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("设置默认库失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("操作失败");
        }
    }
    
    @PostMapping("/order")
    public ResponseEntity<?> setOrder(@RequestParam String key, 
                                    @RequestParam String value) {
        try {
            redisService.setOrder(key, value);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("设置订单库失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("操作失败");
        }
    }
    
    @PostMapping("/user")
    public ResponseEntity<?> setUser(@RequestParam String key, 
                                   @RequestParam String value) {
        try {
            redisService.setUser(key, value);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("设置用户库失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("操作失败");
        }
    }
}

5. 缓存配置(可选)

5.1 代码如下
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 创建多个缓存管理器
        Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
        
        // 默认缓存配置
        cacheConfigs.put("default", RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1)));
            
        // 订单缓存配置
        cacheConfigs.put("order", RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(30)));
            
        // 用户缓存配置
        cacheConfigs.put("user", RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(2)));
        
        return RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig())
            .withInitialCacheConfigurations(cacheConfigs)
            .build();
    }
}

http://www.kler.cn/a/429598.html

相关文章:

  • uniapp 小程序 textarea 层级穿透,聚焦光标位置错误怎么办?
  • 如何制作一个高质量的 Dockerfile 镜像:从入门到实践
  • excel 整理表格,分割一列变成多列数据
  • Three.js 用户交互:构建沉浸式3D体验的关键
  • 不同音频振幅dBFS计算方法
  • 计算机网络 | 什么是公网、私网、NAT?
  • 数据类型转换在自然语言处理中的应用
  • 计算机组成原理(一):计算机指令
  • SparkSQL编程实践
  • ollama-webui - Ollama的ChatGPT 风格的 Web 界面
  • 从零开始的使用SpringBoot和WebSocket打造实时共享文本应用
  • Rust 内置数据结构——BTreeMap应用教程
  • 【教学类-82-01】20241209涂色手表制作1.0(表盘、表带)
  • 基于STM32的手势电视机遥控器设计
  • 使用pyspark完成wordcount案例
  • Flutter 图片编辑板(二) 拖动位置和对齐线应用
  • 封闭式论文写作--全面掌握ChatGPT-4o的写作技能,掌握提示词使用技巧、文献检索与分析方法,帮助您选定研究方向,提炼学术论文题目
  • 软件漏洞印象
  • 网络安全 - Cross-site scripting
  • 刷leetcodehot100-7动态规划
  • 【RBF SBN READ】hadoop社区基于RBF的SBN READ请求流转
  • 产品经理的财会知识课:资产的减值测试
  • X推出新AI图像生成器Aurora:更接近真实的创作效果
  • Facebook与Web3的结合:去中心化社交的可能性
  • 【go】fmt包讲解与案例
  • C语言实例_27之删除字符串中指定字符