1. 在 Spring Boot 中集成 Redis (1)完成配置基礎項。 添加 Redis、MySQL、MyBatis 依賴。 (2)配置MySQL、Redis伺服器 可以直接在application.yml文件中逬行配置,具體配置方法見以下代碼: 查看代碼 # 應用名稱 spring: red ...
1. 在 Spring Boot 中集成 Redis
(1)完成配置基礎項。
添加 Redis、MySQL、MyBatis 依賴。
(2)配置MySQL、Redis伺服器
可以直接在application.yml文件中逬行配置,具體配置方法見以下代碼:
查看代碼
# 應用名稱
spring:
redis:
host: 127.0.0.1
port: 6379
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 5000
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
username: root
password: 123456
thymeleaf:
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
cache: false
prefix: classpath:/static/
mybatis:
# spring boot集成mybatis的方式列印sql
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 應用服務 WEB 訪問埠
server:
port: 8080
(3)在入口類加上@EnableCaching註解,開啟緩存支持。
2. 配置Redis類
要想啟用Spring緩存支持,需創建一個CacheManager的Bean
package com.intehel.demo.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.StringRedisTemplate;
import java.lang.reflect.Method;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
//在緩存對象集合中,緩存是以key-value形式保存的
//如果沒有指定緩存的key,則Spring Boot 會使用SimpleKeyGenerator生成key
@Override
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
//定義緩存key的生成策略
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@SuppressWarnings("rawtypes")
@Bean
//緩存管理器 2.X版本
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);
return cacheManager;
}
//緩存管理器 1.X版本
/* public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate){
return new RedisCacheManager(redisTemplate);
}*/
@Bean
//註冊成Bean被Spring管理,如果沒有這個Bean,則Redis可視化工具中的中文內容都會以二進位存儲,不易檢查
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(factory);
return stringRedisTemplate;
}
}
3.創建測試實體類
創建用於數據操作的測試實體類,見以下代碼:
package com.intehel.demo.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
private Long id;
private String name;
private Integer age;
private String address;
}
4. 實現實體和數據表的映射關係
package com.intehel.demo.mapper;
import com.intehel.demo.domain.Person;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface PersonMapper {
@Insert("insert into person(name, age,address) values(#{name},#{age},#{address})")
int addPerson(@Param("name")String name, @Param("age")String age, @Param("address")String address);
@Select("select * from person where id = #{id}")
Person findById(@Param("id")String id);
@Update("update person set age = #{age},name = #{name},address = #{address} where id = #{id}")
int updateById(Person person);
@Delete("delete from person where id = #{id}")
void deleteById(@Param("id")String id);
}
5. 創建Redis緩存服務層
package com.intehel.demo.service;
import com.intehel.demo.domain.Person;
import com.intehel.demo.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@CacheConfig(cacheNames = "person")
public class PersonService {
@Autowired
PersonMapper personMapper;
@Cacheable(key = "#p0")
public Person selectPerson(String id){
System.out.println("selectPerson");
return personMapper.findById(id);
}
@CachePut(key = "#p0")
public void updatePerson(Person person){
System.out.println("updatePerson");
personMapper.updateById(person);
}
@CacheEvict(key = "#p0",allEntries = true)
public void deletePerson(String id){
System.out.println("deletePerson");
personMapper.deleteById(id);}
}
代碼解釋如下。
- @Cacheable:將查詢結果緩存到Redis中。
- key="#p0":指定傳入的第1個參數作為Redis的key。
- @CachePut:指定key, 將更新的結果同步到Redis中。
- @CacheEvict:指定key, 刪除緩存數據。
- @allEntries=true:方法調用後將立即清除緩存
6.完成增加、刪除、修改和查詢測試API
package com.intehel.demo.controller;
import com.intehel.demo.service.PersonService;
import com.intehel.demo.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class PersonController {
@Autowired
PersonService personService;
@RequestMapping(value = "/{id}")
public Person selectPerson(@PathVariable String id){
return personService.selectPerson(id);
}
@RequestMapping(value = "/update")
public String updatePerson(@RequestBody Person person){
personService.updatePerson(person);
return "success";
}
@RequestMapping(value = "/delete/{id}")
public String deletePerson(@PathVariable String id){
personService.deletePerson(id);
return "delete success";
}
}
啟動項目,多次訪問http://localhost:8080/user/1 第一次時控制台會出現select信息,代表對資料庫進行了查詢操作。後面再訪問時則不會出現提示,表示沒有對資料庫執行操作,而是使用 Redis中的緩存數據。