0%

TaskPoolConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableAsync
public class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}

使用

1
2
@Autowired
private ThreadPoolTaskExecutor taskExecutor;

pom.xml

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

RedisConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* RedisConfig
*
* @author jlin
* @date 2018/11/7 18:44
*/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

/**
* 配置自定义redisTemplate
*
* @return
*/
@Bean
RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);

//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}

RedisTest.java 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* RedisTest
*
* @author jlin
* @date 2018/11/9 09:41
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;

@Test
public void setRedis() {
redisTemplate.opsForValue().set("name", "林剑");
redisTemplate.opsForValue().set("sex", "男");
User user1 = new User();
user1.setUserId(1);
user1.setUserName("张三");
user1.setPassword("123");
User user2 = new User();
user2.setUserId(2);
user2.setUserName("李四");
user2.setPassword("456");
redisTemplate.opsForHash().put("user", String.valueOf(user1.getUserId()), user1);
redisTemplate.opsForHash().put("user", String.valueOf(user2.getUserId()), user2);
}

@Test
public void getRedis() {
System.out.println(JSON.toJSONString(redisTemplate.opsForHash().get("user", "1")));
System.out.println(JSON.toJSONString(redisTemplate.opsForHash().get("user", "2")));
}
}