spring快取與Redis
阿新 • • 發佈:2018-12-19
資料庫配置:
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.官網下載:https://redis.io/download
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 publicinterface 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}。
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的寫法。