前言
如果计划使用SpringBoot连接Redis, 请先配置好使用的redis,并建立基础的SpringBoot工程。
maven中心服务器https://repo.maven.apache.org/maven2/
正文
配置Redis
pom.xml加入dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
application.yml加入redis配置
spring:
redis:
host: 127.0.0.1 #host
port: 6379 #port
database: 10 #使用的数据库(默认0-15选择其中一个)
timeout: 5000 #连接超时时间
jedis:
pool:
max-active: 50 #最大连接数
max-wait: 3000 #阻塞时最大等待时间
max-idle: 20 #最大空闲连接
min-idle: 2 #最小空闲连接
使用
有两种使用方式:
- 作为一种数据库,直接当做数据库来使用
- 作为缓存使用(通过注解)
数据库(以下只针对String => String的方式)
编写基础方法
@Component
public class RedisConfig {
private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);
@Autowired
private RedisTemplate<String, String> redisTemplate;
public String read(String key) {
return redisTemplate.opsForValue().get(key);
}
public void write(String key, String value) {
try {
redisTemplate.opsForValue().set(key, value);
} catch (Exception e) {
log.error("[REDIS SERVICE] Write data failed for {}", e.getMessage());
}
}
public void update(String key, String value) {
try {
redisTemplate.opsForValue().getAndSet(key, value);
} catch (Exception e) {
log.error("[REDIS SERVICE] Update data failed for {}", e.getMessage());
}
}
public void delete(String key) {
redisTemplate.delete(key);
}
public boolean containsKey(String key) {
return !StringUtils.isEmpty(read(key));
}
}
测试使用
public class RedisTest extends MainTest {
@Autowired
RedisConfig redisConfig;
@Test
public void Test_01() {
String key = "test";
String startValue = "start";
String endValue = "end";
redisConfig.write(key, startValue);
System.out.println(redisConfig.read(key));
redisConfig.update(key, endValue);
System.out.println(redisConfig.read(key));
redisConfig.delete(key);
System.out.println(redisConfig.read(key));
}
缓存使用
存储方式建议:使用String => Json的方式,方便数据库中查看
- 存储的时候需要注意序列化的问题
主入口添加自定缓存注解
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
添加配置bean,重写序列化的实现方法
@Configuration
public class RedisConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
redisSerializer.setObjectMapper(om);
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer));
RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(cacheConfiguration).build();
return redisCacheManager;
}
}
需要存储的地方加上对应的注解
建议直接在controller上添加,这样保存和获取的基本就是一致的。具体的注解说明可以自己查看源码,很详细
@RestController
@RequestMapping("/fileDeal")
public class FileController {
@Autowired
private FileService fileService;
@RequestMapping(value = "/fileSearch", method = RequestMethod.POST)
@Cacheable(cacheNames = "FileBean", key = "#fileType + #filePath")
public List<FileBean> searchFileController(@RequestParam("fileType") String fileType,
@RequestParam("filePath") String filePath) {
return fileService.searchFiles(filePath, fileType);
}
}
- 说明一个遇到的问题。这个list因为我在service层使用多线程的时候创建成了List fileList = Collections.synchronizedList(new ArrayList()), 但是不能被反序列化,因此在return的时候,需要return new ArrayList<>(fileList);
- 应该还有其他的地雷,只是我还没有踩到