資料快取到Redis
直接程式碼,這裡沒有使用bean類
專案結構:
1.引入maven依賴
<properties> <java.version>1.8</java.version> <mybatis.version>2.1.0</mybatis.version> <artifactId>springboot-redis</artifactId> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.39</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> </dependencies>
2.配置檔案 application.properties(也可配置到檔案 application.yml)
#資料庫的連線 spring.datasource.url=jdbc:mysql://localhost:3306/work?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Redis資料庫索引(預設為0) spring.redis.database=0 # Redis伺服器地址 spring.redis.host=127.0.0.1 # Redis伺服器連線埠 spring.redis.port=6379 # Redis伺服器連線密碼(預設為空) spring.redis.password= # 連線池最大連線數(使用負值表示沒有限制) spring.redis.jedis.pool.max-active=8 # 連線池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.jedis.pool.max-wait=-1ms # 連線池中的最大空閒連線 spring.redis.jedis.pool.max-idle=8 # 連線池中的最小空閒連線 spring.redis.jedis.pool.min-idle=0 # 連線超時時間(毫秒) spring.redis.timeout=10000ms logging.level.com.lh.springboot.mapper=debug
3.配置檔案application.yml (也可配置到檔案 application.properties)
mybatis: config-location: classpath:/mybatis/mybatis-config.xml # mybatis-config.xml 的檔案地址 mapper-locations: classpath:/mybatis/mapper/*.xml # 所有以.xml 結尾的檔案
4.配置主程式的執行類 (Springbootweb02Application)
1). @MapperScan(value = "com.lh.springboot.mapper")
該註解的意思是:指定要變成實現類的介面所在的包,然後包下面的所有介面在編譯之後都會生成相應的實現類
2). @EnableCaching
該註解的意思是:開啟快取管理功能
3). @SpringBootApplication
該註解的意思是:這個類是主程式類
5.配置config包下的類
//配置檔案 RedisConfig
package com.lh.springboot.config;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration //用於定義配置類,可替換xml配置檔案,被註解的類內部包含有一個或多個被@Bean註解的方法
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> empRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws Exception {
RedisTemplate<Object,Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// Json序列化配置
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(serializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory){
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600)) //存入Redis的時間設定600秒
//.entryTtl(Duration.ofDays(1))
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();}
}
//配置檔案 Myconfig
package com.lh.springboot.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * @program: springbootweb01 * @description: 配置類 * @author: li hui * @create: 2020-12-18 19:52 */ //@EnableWebMvc 全面接管mvc @Configuration public class MyConfig extends WebMvcConfigurationSupport {
//該類可不寫 }
6.建立 mapper(包)下的UsersDao介面
//UserDao的介面
package com.lh.springboot.mapper; import org.apache.ibatis.annotations.Mapper; import java.util.List; import java.util.Map; @Mapper //該註解是在編譯之後會生成相應的介面實現類 (在主程式類註解了 @MapperScan() 在此處就可以省略) public interface UsersDao{ Object test(Map map); Integer updTest(Map map); Integer delTest(Map map); List<?> queryTest(); }
7.配置 mybatis包下的檔案
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration>
<!--mybatis-config.xml 檔案--> <!--<settings> <!– 列印查詢語句 –> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>--> <!--mybatis的外掛配置--> </configuration>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lh.springboot.mapper.UsersDao"> <!--UserDao介面的全路徑--> <!--UsersMapper.xml檔案--> <select id="test" parameterType="map" resultType="map"> select * from users where id=#{id}; </select> <update id="updTest" parameterType="map"> update users set username=#{username},password=#{password},phone=#{phone},IDnumber=#{IDnumber} where id=#{id} </update> <delete id="delTest" parameterType="map"> delete from users where id=#{id} </delete> <select id="queryTest" resultType="map"> select username,password,phone,IDnumber,id from users </select> </mapper>
8.建立service包下的介面和 impl包下的實現類
//UserService 的介面
package com.lh.springboot.service; import java.util.List; import java.util.Map; public interface UsersService{ Object test(Map map); Map updTest(Map map); Integer delTest(Map map); List<?> queryTest(); }
//UsersServiceImpl (實現UsersService介面) 快取註解也在本類來執行
package com.lh.springboot.service.impl; import com.lh.springboot.mapper.UsersDao; import com.lh.springboot.service.UsersService; 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; import java.util.List; import java.util.Map; @Service("usersService") public class UsersServiceImpl implements UsersService { private final UsersDao usersDao; @Autowired public UsersServiceImpl(UsersDao usersDao) { this.usersDao = usersDao; } @Override @Cacheable(cacheNames = {"test"}, key = "'user_'+#map.get('id')",unless="#result==null") public Object test(Map map) { System.out.println("測試query"); return usersDao.test(map); } @Override @CachePut(cacheNames = {"test"}, key = "'user_'+#map.get('id')",unless="#result==null") public Map updTest(Map map) { System.out.println("測試upd"); Integer integer = usersDao.updTest(map); if(integer==1){ return map; }else { return null; } } @Override @CacheEvict(cacheNames = "test", key = "'user_'+#map.get('id')",allEntries=false,beforeInvocation=false) public Integer delTest(Map map) { System.out.println("測試del"); return usersDao.delTest(map); } @Override @Cacheable(cacheNames = {"queryTest"},unless="#result==null") public List<?> queryTest() {
System.out.println("測試query全查") List<?> objects = usersDao.queryTest(); if(objects.size()<=0){ return null; }else { return objects; } }
/* @Cacheable 將方法的執行結果進行快取 @Cacheable 以後再要相同的資料 直接從快取中獲取 就不用在執行方法了 幾個屬性 value/cacheNames 指定快取的名字 key 快取資料使用的key,預設使用方法引數的值 keyGenerator:key的生成器,可以自己指定key的生成器的元件id key/keyGenerator: 二選一 cacheManager:指定快取管理器 或者cacheResolver指定快取解析器 二選一 condition:指定符合條件的情況下才快取 unless:否定快取,當unless指定的條件是true,我們的方法返回值就不會被快取 可以獲取到結果進行判斷 sync:是否使用非同步模式 */ /* @CachePut 快取更新 @CacheEvict 清楚快取 */
}
9.建立controller包下的類
package com.lh.springboot.controller; import com.alibaba.fastjson.JSON; import com.lh.springboot.service.UsersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @Controller @Scope("prototype") public class UsersController{ private final UsersService usersService; @Autowired public UsersController(UsersService usersService) { this.usersService = usersService; } @GetMapping(value = "/aa") @ResponseBody public Object aa(@RequestParam Map map){ return usersService.test(map); } @GetMapping(value = "/bb") @ResponseBody public Map bb(@RequestParam Map map){ return usersService.updTest(map); } @GetMapping(value = "/cc") @ResponseBody public Integer cc(@RequestParam Map map){ return usersService.delTest(map); } @GetMapping(value = "/dd") @ResponseBody public String dd(){ List<?> objects = usersService.queryTest(); return JSON.toJSONString(objects); } }
10.啟動主程式類
11,開啟網頁進行測試
1.mysql資料庫的值為
2.啟動Redis資料庫 (此時無資料)
3.訪問 http://127.0.0.1:8080/aa?id=1 返回id為1的資料
1)檢視Redis的資料 此時資料存到了Redis裡有效時間600秒
2)檢視控制檯上的輸出
可以看出,程式訪問了mysql資料表
3)重新整理頁面 再次檢視控制檯輸出
4)修改資料(修改快取) 檢視控制檯輸出 http://127.0.0.1:8080/bb?username=00&password=00&phone=00&IDnumber=00&id=1
可以看出 我修改一條資料控制檯也有列印,Redis的值也隨著發生變化
5)再次查詢id為1的資料 http://127.0.0.1:8080/aa?id=1
再次檢視控制檯
當我們修改結束,再次檢視資料,沒有輸出 就是直接查的是Redis的快取資料沒有查詢mysql的表資料
6)清除快取 http://127.0.0.1:8080/cc?id=1 (刪除id為1的資料)
刪除成功
Redis資料也確實刪除了
我們再次查詢刪除的id為1的資料
快取也清除成功!