zoukankan      html  css  js  c++  java
  • springboot+redis实现缓存数据

      在当前互联网环境下,缓存随处可见,利用缓存可以很好的提升系统性能,特别是对于查询操作,可以有效的减少数据库压力,Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,Redis 的优势包括它的速度、支持丰富的数据类型、操作原子性,以及它的通用性。SpringBoot:一款Spring框架的子框架,也可以叫微服务框架,SpringBoot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,能够极大的简化基于SpringMVC的Web应用和REST服务开发。本篇介绍注解方式在springboot项目中使用redis做缓存。

      1、在pom.xml中引入相关依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>    

      2、配置redisconfig,在实际项目中可以通过配置KeyGenerator来指定缓存信息的key的生成规则

    package com.example.demo;
    
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
    
        @Bean
        public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
            RedisCacheManager rm = new RedisCacheManager(redisTemplate);
            rm.setDefaultExpiration(30l);// 设置缓存时间
            return rm;
        }
    
        // @Bean
        // public KeyGenerator myKeyGenerator(){
        // return new KeyGenerator() {
        // @Override
        // public Object generate(Object target, Method method, Object... params) {
        // StringBuilder sb = new StringBuilder();
        // sb.append(target.getClass().getName());
        // sb.append(method.getName());
        // for (Object obj : params) {
        // sb.append(obj.toString());
        // }
        // return sb.toString();
        // }
        // };
        //
        // }
    
        @Bean
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            StringRedisTemplate template = new StringRedisTemplate(factory);
            @SuppressWarnings({ "rawtypes", "unchecked" })
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return template;
        }
    }

      3、创建实体类

    package com.example.demo;
    
    public class User {
    
        public User() {
        }
        
        private int id;
        private String name;
        private int age;
        public User(int id, String name, int age) {
            super();
            this.id = id;
            this.name = name;
            this.age = age;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        
    }

      4、service类,使用注解来做缓存

    package com.example.demo;
    
    import java.util.Date;
    
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService {
    
        // @Cacheable缓存key为name的数据到缓存usercache中
        @Cacheable(value = "usercache", key = "#p0")
        public User findUser(String name) {
            System.out.println("无缓存时执行下面代码,获取zhangsan,Time:" + new Date().getSeconds());
            return new User(1, "zhangsan", 13);// 模拟从持久层获取数据
        }
    
        // @CacheEvict从缓存usercache中删除key为name的数据
        @CacheEvict(value = "usercache", key = "#p0")
        public void removeUser(String name) {
            System.out.println("删除数据" + name + ",同时清除对应的缓存");
        }
    
        // @CachePut缓存新增的数据到缓存usercache中
        @CachePut(value = "usercache", key = "#p0")
        public User save(String name, int id) {
            System.out.println("添加lisi用户");
            return new User(2, "lisi", 13);
        }
    
        @Cacheable(value = "usercache", key = "#p0")
        public User findUser2(String name) {
            System.out.println("无缓存时执行下面代码,获取lisi,Time:" + new Date().getSeconds());
            return new User(2, "lisi", 13);// 模拟从持久层获取数据
        }
    }

      5、控制器类

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MyController {
    
        @Autowired
        UserService userService;
    
        @GetMapping("/finduser1")
        public User finduser1() {
            return userService.findUser("zhangsan");
        }
    
        @GetMapping("/finduser2")
        public User finduser2() {
            return userService.findUser2("lisi");
        }
    
        @GetMapping("/adduser2")
        public User adduser2() {
            return userService.save("lisi", 13);
        }
    
        @GetMapping("/delete")
        public void removeUser() {
            userService.removeUser("zhangsan");
        }
    }

      6、配置信息,这里使用docker在本地虚拟机启动一个redis服务

    spring.redis.database=0
    spring.redis.host=192.168.86.133
    spring.redis.password=
    spring.redis.port=6379
    spring.redis.pool.max-idle=8
    spring.redis.pool.min-idle=0  
    spring.redis.pool.max-active=100 
    spring.redis.pool.max-wait=-1

      启动redis服务,然后启动本springboot项目,通过访问对应的url,可以看到在进行数据增删改查的时候是有缓存的。

  • 相关阅读:
    leetcode 576. Out of Boundary Paths 、688. Knight Probability in Chessboard
    leetcode 129. Sum Root to Leaf Numbers
    leetcode 542. 01 Matrix 、663. Walls and Gates(lintcode) 、773. Sliding Puzzle 、803. Shortest Distance from All Buildings
    leetcode 402. Remove K Digits 、321. Create Maximum Number
    leetcode 139. Word Break 、140. Word Break II
    leetcode 329. Longest Increasing Path in a Matrix
    leetcode 334. Increasing Triplet Subsequence
    leetcode 403. Frog Jump
    android中webView加载H5,JS不能调用问题的解决
    通过nginx中转获取不到IP的问题解决
  • 原文地址:https://www.cnblogs.com/hhhshct/p/9002648.html
Copyright © 2011-2022 走看看