SpringBoot整合Redis入門之緩存數(shù)據(jù)的方法
前言
Redis是一個(gè)開源的使用ANSI C語言編寫、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。從2010年3月15日起,Redis的開發(fā)工作由VMware主持。從2013年5月開始,Redis的開發(fā)由Pivotal贊助。
為什么要使用Redis呢?
舉個(gè)例子,假如系統(tǒng)中有2千萬用戶信息,用戶信息基本固定,一旦錄入很少變動(dòng),那么你每次加載所有用戶信息時(shí),如果都要請求數(shù)據(jù)庫,數(shù)據(jù)庫編譯并執(zhí)行你的查詢語句,這樣效率就會(huì)低下很多,針對這種信息不經(jīng)常變動(dòng)并且數(shù)據(jù)量。
較大的情況,通常做法,就是把他加入緩存,每次取數(shù)前先去判斷,如果緩存不為空,那么就從緩存取值,如果為空,再去請求數(shù)據(jù)庫,并將數(shù)據(jù)加入緩存,這樣大大提高系統(tǒng)訪問效率。
相關(guān)依賴
<!-- springboot版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.7.RELEASE</version> </parent> <!-- 依賴 --> <dependencies> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 通用池 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>
配置
# 端口 server: port: 9998 # mysql數(shù)據(jù)源 spring: datasource: username: root password: root url: jdbc:mysql://127.0.0.1:3306/dbtest?serverTimezone=GMT%2B8 # redis redis: host: localhost port: 6379 timeout: 1000 jedis: pool: min-idle: 5 max-idle: 10 max-wait: -1 # mybatis mybatis: mapper-locations: classpath:/mybatis/mapper/*.xml type-aliases-package: cn.kgc.entities # 開啟駝峰命名 configuration: map-underscore-to-camel-case: true # log logging: level: cn.kgc: debug
數(shù)據(jù)庫
#建表 CREATE TABLE `emp` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(11) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; #插入數(shù)據(jù) INSERT INTO `emp` VALUES (1, '張三', 18); INSERT INTO `emp` VALUES (2, '李四', 20); INSERT INTO `emp` VALUES (3, '王五', 22);
實(shí)體類
Emp
@Data @Table(name = "emp") public class Emp implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private Integer age; }
RedisConfig
指定Redis序列化方式
@Configuration public class RedisConfig { @Bean public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){ RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); // 指定kv的序列化方式 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setKeySerializer(new StringRedisSerializer()); return redisTemplate; } }
Mapper
Emp的Mapper接口繼承tk的Mapper類,泛型為實(shí)體類Emp
public interface EmpMapper extends Mapper<Emp> { }
Service接口
業(yè)務(wù)接口定義add添加和getEmpById根據(jù)id查詢的方法
public interface EmpService { public void add(Emp emp); public Object getEmpById(Integer id); }
Service實(shí)現(xiàn)類
先查Redis,Redis沒有數(shù)據(jù)再從數(shù)據(jù)庫中拿數(shù)據(jù),同時(shí)緩存到Redis中。
@Service @Slf4j public class EmpServiceImpl implements EmpService { @Autowired public RedisTemplate redisTemplate; @Resource private EmpMapper empMapper; @Override public void add(Emp emp) { empMapper.insert(emp); } @Override public Object getEmpById(Integer id) { // 先從緩存獲取數(shù)據(jù),如果有則直接返回 // 如果無,則查詢mysql,并將數(shù)據(jù)設(shè)置到緩存 String key = "user:" + id; Object userObj = redisTemplate.opsForValue().get(key); if(userObj == null){ synchronized (this.getClass()){ userObj = redisTemplate.opsForValue().get(key); if(userObj == null ){ log.debug("----> 查詢數(shù)據(jù)庫.............."); // 查數(shù)據(jù)庫 Emp emp = empMapper.selectByPrimaryKey(id); redisTemplate.opsForValue().set(key,emp); return emp; }else{ log.debug("----> 查詢緩存(同步代碼塊)>>>>>>>>>>>>>>>>>"); return userObj; } } }else{ log.debug("----> 查詢緩存>>>>>>>>>>>>>>>>>"); } return userObj; } }
測試Redis
Redis-Controller
@RestController public class RedisContoller { @Autowired private RedisTemplate redisTemplate; @GetMapping("/redis/get/{key}") public Object get(@PathVariable("key") String key){ return redisTemplate.opsForValue().get(key); } @PostMapping("/redis/set/{key}/{value}") public Object set(@PathVariable("key") String key, @PathVariable("value") String value){ redisTemplate.opsForValue().set(key,value); return "set success"; } }
Controller
Redis+MySQL
@RestController public class EmpController { @Autowired private EmpService empService; @PostMapping("/emp") public String addEmp(Emp emp){ empService.add(emp); return "add ok"; } @GetMapping("/emp/{id}") public Object getEmpById(@PathVariable("id") Integer id){ ExecutorService es = Executors.newFixedThreadPool(200); for(int i=0 ;i<500;i++){ es.submit(new Runnable() { @Override public void run() { empService.getEmpById(id); } }); } return empService.getEmpById(id); } }
到此這篇關(guān)于SpringBoot整合Redis入門之緩存數(shù)據(jù)的文章就介紹到這了,更多相關(guān)SpringBoot整合Redis緩存數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于redis實(shí)現(xiàn)定時(shí)任務(wù)的方法詳解
這篇文章主要給大家介紹了基于redis實(shí)現(xiàn)定時(shí)任務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用redis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Redis集群水平擴(kuò)展、集群中添加以及刪除節(jié)點(diǎn)的操作
這篇文章主要介紹了Redis集群水平擴(kuò)展、集群中添加以及刪除節(jié)點(diǎn)的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Linux服務(wù)器使用Redis作為數(shù)據(jù)緩存并用log4j2進(jìn)行日志記錄的過程分享
這篇文章主要介紹了Linux服務(wù)器使用Redis作為數(shù)據(jù)緩存并用log4j2日志記錄,關(guān)于SpringBoot項(xiàng)目配置Redis與log4j2是查詢官方文檔,本文中的Redis配置類、Redis工具類以及l(fā)og4j2.xml配置文件來自網(wǎng)絡(luò),查證源自何處比較麻煩,所以在此感謝所有人的分享2023-09-09Linux系統(tǒng)下安裝Redis數(shù)據(jù)庫過程
大家好,本篇文章主要講的是Linux系統(tǒng)下安裝Redis數(shù)據(jù)庫過程,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12