摘要
本文章用于SpringBoot项目构建Bean对象
构建两种对象(RedisConfig + RestTemplateConfig)
使用 @Autowired 方式注入直接使用即可
1. 构建RedisConfig Bean对象
①依赖
<!--redis -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<!--redis锁-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.13.6</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.10.1</version>
</dependency>
②配置文件
#redis
spring.redis.database=15
spring.redis.host=xxx
spring.redis.port=xxx
spring.redis.password=xxx
spring.redis.pool.max-active=200
spring.redis.jedis.pool.max-wait= -1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout = 10000
③代码
@Configuration
public class RedisConfig {
/**
*
* @param factory factory
* @author liudz
* @date 2021/1/6
* @return 执行结果
**/
@Bean(name = "redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
2. 构建RestTemplateConfig Bean对象
代码
@Configuration
public class RestTemplateConfig {
/**
*
* @param factory factory
* @author liudz
* @date 2021/1/6
* @return 执行结果
**/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
/**
*
* @author liudz
* @date 2021/1/6
* @return 执行结果
**/
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(Integer.parseInt("5000"));
factory.setConnectTimeout(Integer.parseInt("15000"));
return factory;
}
}