名稱java |
解釋 |
Cache | 緩存接口,定義緩存操做。實現有:RedisCache、EhCacheCache、ConcurrentMapCache等 |
CacheManager | 緩存管理器,管理各類緩存(cache)組件 |
@Cacheable | 主要針對方法配置,可以根據方法的請求參數對其進行緩存 |
@CacheEvict | 清空緩存 |
@CachePut | 保證方法被調用,又但願結果被緩存與@Cacheable區別在因而否每次都調用方法,經常使用於更新 |
@EnableCaching | 開啓基於註解的緩存 |
keyGenerator | 緩存數據時key生成策略 |
serialize | 緩存數據時value序列化策略 |
@CacheConfig | 統一配置本類的緩存註解的屬性 |
安裝dockermysql
yum -y install docker-ce
開機啓動dockerweb
systemctl start docker
檢驗docker是否安裝成功redis
docker version
docker安裝redisspring
docker pull redis
docker檢測是否安裝成功redissql
docker images
docker啓動redis並設置端口映射(-d表示後臺運行)docker
docker run -p 6379:6379 -d redis:latest myredis
查看redis是否啓動成功數據庫
docker ps
在看代碼前先看看目錄結構吧(在這裏使用ssm來整合redis)apache
數據庫表結構緩存
pom.xml文件,這裏主要是引入spring-boot-starter-cache依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- mybatis 與 spring boot 2.x的整合包 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--mysql JDBC驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> </dependencies>
配置文件application.yml,配置redis
spring:
datasource:
url: jdbc:mysql://localhost:3306/spring_boot_cache?useUnicode=true
driver-class-name: com.mysql.jdbc.Driver
username: root
password: lzh
redis:
# 這是redis所在服務器的ip
host: 192.168.126.129
timeout: 10000ms
database: 0
lettuce:
pool:
max-wait: -1ms
max-active: 8
max-idle: 8
min-idle: 0
cache:
type: redis
啓動類加入@EnableCaching註解
package com.lzh.springbootstudytestcache; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class SpringBootStudyTestCacheApplication { public static void main(String[] args) { SpringApplication.run(SpringBootStudyTestCacheApplication.class, args); } }
UserController 類暴露接口
package com.lzh.springbootstudytestcache.controller; import com.lzh.springbootstudytestcache.model.User; import com.lzh.springbootstudytestcache.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author lzh * create 2019-09-24-20:34 */ @RestController public class UserController { @Autowired UserService userService; @GetMapping("/user/save") public User saveUser(@RequestParam Integer id,@RequestParam String name,@RequestParam Integer age){ User user= userService.save(new User(id,name,age)); return user; } @GetMapping("/user/{id}") public User getUserById(@PathVariable Integer id){ System.out.println("id="+id); User user = userService.findUserById(id); System.out.println("getUserById - "+user); return user; } @GetMapping("/user/update") public User updateUser(@RequestParam Integer id,@RequestParam String name,@RequestParam Integer age){ User user= userService.updateUser(new User(id,name,age)); return user; } @GetMapping("/user/del/{id}") public String deleteUser(@PathVariable Integer id){ System.out.println("id="+id); int num = userService.deleteUser(id); if (num > 0){ return "刪除成功"; } else { return "刪除失敗"; } } }
UserService接口
package com.lzh.springbootstudytestcache.service; import com.lzh.springbootstudytestcache.model.User; /** * @author lzh * create 2019-09-24-9:14 */ public interface UserService { User save(User user); User findUserById(Integer id); User updateUser(User user); int deleteUser(Integer id); }
UserService實現類
package com.lzh.springbootstudytestcache.service.impl; import com.lzh.springbootstudytestcache.mapper.UserMapper; import com.lzh.springbootstudytestcache.model.User; import com.lzh.springbootstudytestcache.service.UserService; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; /** * @author lzh * create 2019-09-24-9:14 */ @Service @Log4j2 public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Cacheable(value = "user",key = "#user.id") @Override public User save(User user) { int saveNum = userMapper.saveUser(user); System.out.println("saveNum="+saveNum); return user; } @Cacheable(value = "user",key = "#id") @Override public User findUserById(Integer id) { log.info("進入findUserById方法"); return userMapper.findUserById(id); } @CachePut(value = "user", key = "#user.id") @Override public User updateUser(User user) { int num = userMapper.updateUser(user); System.out.println("num="+num); return user; } @CacheEvict(value = "user") @Override public int deleteUser(Integer id) { return userMapper.deleteUser(id); } }
User實體類,加入@Data至關於加入getset方法,@AllArgsConstructor全參構造方法,@ToString重寫tostring方法,引入Lombok簡化代碼
package com.lzh.springbootstudytestcache.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.ToString; import java.io.Serializable; /** * @author Levin * @since 2018/5/10 0007 */ @Data @AllArgsConstructor @ToString public class User implements Serializable { private Integer id; private String name; private Integer age; }
UserMapper持久層,使用mybatis註解@Select、@Update、@Insert、@Delete實現
package com.lzh.springbootstudytestcache.mapper; import com.lzh.springbootstudytestcache.model.User; import org.apache.ibatis.annotations.*; /** * @author lzh * create 2019-09-24-20:39 */ @Mapper public interface UserMapper { @Select("SELECT * FROM User WHERE id = #{id}") User findUserById(Integer id); @Update("update user set name=#{name},age=#{age} where id=#{id}") int updateUser(User user); @Insert("insert into user set name=#{name},age=#{age}") int saveUser(User user); @Delete("DELETE FROM USER WHERE id=#{id}") int deleteUser(Integer id); }
改變默認jdk序列化器
package com.lzh.springbootstudytestcache.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.*; /** * @author lzh * create 2019-09-24-22:22 */ import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import java.time.Duration; //@Configuration public class MyRedisConfig { //@Bean(name = "redisTemplate") public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(keySerializer()); redisTemplate.setHashKeySerializer(keySerializer()); redisTemplate.setValueSerializer(valueSerializer()); redisTemplate.setHashValueSerializer(valueSerializer()); return redisTemplate; } //@Primary //@Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){ //緩存配置對象 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //設置緩存的默認超時時間:30分鐘 .disableCachingNullValues() //若是是空值,不緩存 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) //設置key序列化器 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); //設置value序列化器 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } private RedisSerializer<String> keySerializer() { return new StringRedisSerializer(); } private RedisSerializer<Object> valueSerializer() { return new GenericJackson2JsonRedisSerializer(); } }
啓動srpingboot訪問http://localhost:8080/user/1
使用redis可視化工具查看發現多了一個user對象,這就是在執行查詢語句的時候保存的緩存
看控制檯這裏打印出了日誌,這是第一次查詢,說明執行了sql語句
再次訪問http://localhost:8080/user/1,沒有執行findUserById方法說明沒有執行sql語句,而是直接從redis緩存中讀取