Resid使用一

本文介绍了如何在SpringBoot项目中配置并使用Redis。首先,需要在pom.xml添加依赖,并在application.yml中配置Redis。接着,讨论了两种使用方式:作为数据库和作为缓存。作为数据库时,提供了基础操作方法。作为缓存,推荐使用String => Json存储,注意序列化问题。同时,展示了如何添加自定义缓存注解和配置bean,以及在遇到的多线程环境下List对象反序列化问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

如果计划使用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);
  • 应该还有其他的地雷,只是我还没有踩到
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值