redis 在spring boot工程中的应用(四) 图片的读取与缓存 byte string

图片由于文件比较大,常用的图片如多采用读取数据库或者文件的方式会加大系统的负载。采用缓存保存的方法可以增加效率。

http://stackoverflow.com/questions/13215024/weird-redis-key-with-spring-data-jedis 这里已经提供了图片的读取方法和类型转换方法,修改一下即可。

本文采用的是,将工程下的文件读入到redis缓存缓存数据库中。

读取文件和编码图片为字符串

    public static String encodeToString(BufferedImage image, String type) {  //将<span style="font-family: Arial, Helvetica, sans-serif;">BufferedImage 转化为string,type是文件类型:jpg,png等</span>
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是Java使用注解操作Redis的示例: 首先,我们需要在pom.xml文件添加Redis的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,我们需要在Spring Boot的Application类上添加@EnableCaching注解来开启缓存: ```java @SpringBootApplication @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 然后,我们需要在Redis的配置文件application.properties添加Redis的连接信息: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 接下来,我们就可以使用注解来操作Redis了。下面是一个使用注解操作Redis缓存的示例: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "userCache", key = "#id") public User getUserById(Long id) { System.out.println("从数据库获取用户信息"); return userRepository.findById(id).orElse(null); } @CachePut(value = "userCache", key = "#user.id") public User saveUser(User user) { System.out.println("保存用户信息到数据库"); return userRepository.save(user); } @CacheEvict(value = "userCache", key = "#id") public void deleteUserById(Long id) { System.out.println("从数据库删除用户信息"); userRepository.deleteById(id); } } ``` 上面的示例,我们使用了三个注解来操作Redis缓存: - @Cacheable:表示方法的结果可以被缓存,如果缓存有数据,则直接返回缓存数据,否则执行方法并将结果放入缓存。 - @CachePut:表示方法的结果需要被缓存,每次都会执行方法,并将结果放入缓存。 - @CacheEvict:表示方法会从缓存删除数据。 在这个示例,我们使用了value属性来指定缓存的名称,key属性来指定缓存的键,#id和#user.id是SpEL表达式,用于获取方法参数的值。 以上就是一个使用注解操作Redis缓存的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GDRetop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值