1.下面是在Spring Boot中配置多个Redis数据库的几种方式:
1.1 配置如下
# application. yml
spring: redis: host: localhostport: 6379 password: your_password# 连接池配置lettuce: pool: max- active: 8 max- idle: 8 min- idle: 0 max- wait: - 1 mstimeout: 5000 ms# 多个数据库配置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) ; 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 ( ) ; }
}