您的位置:首页 > 游戏 > 手游 > 07年以前东莞有多乱_上海建设工程招标网_日本免费服务器ip地址_北京seo网站优化公司

07年以前东莞有多乱_上海建设工程招标网_日本免费服务器ip地址_北京seo网站优化公司

2024/12/23 8:04:50 来源:https://blog.csdn.net/weixin_45069056/article/details/144351077  浏览:    关键词:07年以前东莞有多乱_上海建设工程招标网_日本免费服务器ip地址_北京seo网站优化公司
07年以前东莞有多乱_上海建设工程招标网_日本免费服务器ip地址_北京seo网站优化公司

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

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

2. Redis配置类

2.1代码如下
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig {@Bean@Primarypublic 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@Primarypublic 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>() {@Overridepublic Object execute(RedisOperations operations) throws DataAccessException {operations.opsForValue().set("key1", "value1");operations.opsForValue().set("key2", "value2");return null;}});redisTemplate1.executePipelined(new SessionCallback<Object>() {@Overridepublic 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 {@Autowiredprivate 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 {@Beanpublic 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();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com