zoukankan      html  css  js  c++  java
  • spring缓存与Redis

    数据库配置:

    spring.datasource.url=jdbc:mysql://localhost:3306/spring_cache
    spring.datasource.username=root
    spring.datasource.password=111111

    Redis配置:

    spring.redis.host=127.0.0.1

    Redis的下载安装:

    1.官网下载:redis

    2.启动redis:进入redis目录下redis-server.exe redis.windows.conf即可。

    3.安装RedisDesktopManager,百度找个破解版。

    开启缓存(主程序):

    @EnableCaching
    

    Mybatis包扫描:

    @MapperScan("com.chriswei.cache.mapper")
    //在Main类上

    Service配置:

    //指定缓存块的名字,全局,用在类名
    @CacheConfig(cacheNames = "emp")
    public class EmployeeService {}
    //指定缓存块的名字,用在方法
    @Cacheable(cacheNames = "emp")
    public Employee getEmployee(Integer id){}
    //更新数据库后更新缓存(分先后)
    //key还可以用result等,除此之外还有condition跟unless可以用
    @CachePut(value = "emp",key = "#employee.id")
    public Employee updateEmployee(Employee employee){}
    //清除缓存
    @CacheEvict(value = "emp",key = "#id")
    public String deleteEmployee(Integer id){}

    除此之外,Key还可以换成keyGenerator,自己指定一个Key的生成策略。

    Mybatis的CRUD:

    @Mapper
    public interface EmployeeMapper {
        @Select("SELECT * FROM EMPLOYEE WHERE ID = #{ID}")
        public Employee getEmployeeById(Integer id);
    
        @Update("UPDATE EMPLOYEE SET LASTNAME=#{lastName},EMAIL=#{email},GENDER=#{gender},DID=#{dId} WHERE ID=#{id}")
        public void updateEmployee(Employee employee);
    
        @Delete("DELETE FROM EMPLOYEE WHERE ID=#{ID}")
        public void deleteEmployeeById(Integer id);
    
        @Insert("INSERT INTO EMPLOYEE(LASTNAME,EMAIL,GENDER,DID) VALUES(#{lastName},#{email},#{gender},#{dId})")
        public void insertEmployee(Employee employee);
    }
    //只需要写接口就行了
    //特别注意,SQL语句中的实体类属性要区分大小写,#{lastName}不能写成#{LASTNAME}。

    另外,关于@Param标签,有时候或者只有一个数据传入的时候,往往不需要也能映射到,但是有多个参数的时候,就需要加上,不然会出现映射不到的情况。

    报错类型为:error:nested exception is org.apache.ibatis.binding.BindingException: Parameter 'newNote' not found. Available parameters are [0, 1, param1, param2]

        @Update("Update TODOLIST SET note=#{newNote} where note=#{oldNote}")
        public void updateNote(@Param("oldNote")String oldNote, @Param("newNote")String newNote);

    pom依赖:(Mybatis都被集成了,主要就是引入Redis的starter)

    官网导航:https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#using-boot-starter

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>

    Redis模板操作:

        @Autowired
        StringRedisTemplate stringRedisTemplate;
    
        @Autowired
        RedisTemplate redisTemplate;

    如使用redisTemplate.opsForXXX.XX()来操作。

    重点:使用Redis存储数据的转JSON操作。

    得写一个独立的CacheManager 来处理,不然存入redis里的是JDBC的格式化数据。

        @Bean
        public CacheManager cacheManager(RedisConnectionFactory factory) {
            RedisSerializer<String> redisSerializer = new StringRedisSerializer();
            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);
    
            // 配置序列化(解决乱码的问题)
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofHours(3))
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                    .disableCachingNullValues();
    
            RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                    .cacheDefaults(config)
                    .build();
            return cacheManager;
        }

    特别注意CacheManager的写法,springboot1.5跟2.0是有差别的,上面是2.0的写法。



  • 相关阅读:
    windows下命令行
    利用border画三角形
    正则
    flex布局
    css笔记
    W3C标准
    SEO相关
    左边固定,右边自适应(解决方案)
    容错性测试的测试点
    Charles安装及使用教程
  • 原文地址:https://www.cnblogs.com/chrisweiii/p/10144761.html
Copyright © 2011-2022 走看看