您好,登錄后才能下訂單哦!
這篇文章主要介紹“SpringBoot如何使用Redis緩存”,在日常操作中,相信很多人在SpringBoot如何使用Redis緩存問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringBoot如何使用Redis緩存”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
1 redis是安裝在linux上
安裝docker
yum install docker
2)開啟docker
service docker start
2 安裝Redis
可到這個網站查怎么安裝 https://hub.docker.com
開啟redis
3 創建springBoot項目(細節不在贅述)
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mao</groupId> <artifactId>spring-cache</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-cache</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</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>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
</project>
4 提供一個entity類 //這個文件來自尚學堂里的
public class Employee implements Serializable
private Integer id; private String lastName; private String email; private Integer gender; //性別 1男 0女 private Integer dId;
。。。。。。(簡寫啦)
}
5 redis的客戶請自己安裝
相關知識點請到這個網站學習 http://www.redis.cn 里面有很多案例
6 配置屬性 application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring_cache
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#啟動駝峰命名法
mybatis.configuration.map-underscore-to-camel-case=true
logging.level.mao.springcache.mapper=debug
#由于我安裝的redis沒密碼,只給主機地址就可以啦
spring.redis.host=192.168.1.139
7 測試下Redis的緩存首先看下源碼是怎么寫的
public class SpringCacheApplicationTests {
//操作鍵值對,jdk默認的序列化機制 @Autowired RedisTemplate redisTemplate; //操作字符串 @Autowired StringRedisTemplate stringRedisTemplate; @Autowired RedisTemplate<Object,Employee> redisTemplate1; [@Test](https://my.oschina.net/azibug) public void test1(){ //stringRedisTemplate.opsForValue().append("hello","hello"); System.out.println(stringRedisTemplate.opsForValue().get("hello")); } [@Test](https://my.oschina.net/azibug) public void test2(){ Employee employee = employeeMapper.getEmployee(1); redisTemplate.opsForValue().set("emp-01",employee); } @Test public void contextLoads() { Employee employee = employeeMapper.getEmployee(1); System.out.println(employee.toString()); }
}
上面test1測試結果:
上面test2測試結果:
接下來解決上面難看的問題:我們重寫RedisTemplate 我們想讓緩存查看的時候為json
@Configuration
public class myredis {
@Bean public RedisTemplate<Object, Employee> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object,Employee> template = new RedisTemplate<Object, Employee>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class); template.setDefaultSerializer(ser); return template; } }
之前一張圖已經展示過原理
下面這張圖解釋這句haul template.setDefaultSerializer(ser);
重新測試的結果
8 接下啦講spring項目中使用 //EmployeeService類
@Service
public class EmployeeService {
@Autowired EmployeeMapper employeeMapper; //將方法的結果緩存,以后請求相同的數據,直接從緩存中獲取,不用調用方法 //CacheManner管理多個Cache組件,對緩存的真正CRUD組件,每個緩存組有自己唯一一個名字 //幾個屬性,指定緩存的名字key,可以指定@param id @Cacheable(cacheNames ={"emp"}) public Employee getEmp(Integer id){ System.out.println("查詢"+id+"員工"); Employee employee = employeeMapper.getEmployee(id); return employee; } //達到了同步更新緩存的目的,取緩存的key要與放緩存的key相同 @CachePut(cacheNames = "emp",key = "#employee.id") public Employee updateEmp(Employee employee){ employeeMapper.updateEmp(employee); return employee; } @CacheEvict(value = "emp",key = "#id") public void deleteEmp(Integer id){ System.out.println("deleteEMp"+id); public Employee getEmployeeByLastName(String lastName){ return employeeMapper.getEmpByLastName(lastName); }
}
EmployeeMapper代碼
public interface EmployeeMapper {
@Select("select * from employee where id =#{id}") public Employee getEmployee(Integer id); @Update("update employee set lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} where id =#{id}") public void updateEmp(Employee employee); @Delete("delete * from employee where id=#{id}") public void deleteEmpById(Integer id); @Insert("insert into employee(lastName,email,gender,d_id) values(#{lastName},#{email},#{gender},#{dId})") public void insertEmpployee(Employee employee); @Select("select * from employee where lastName=#{lastName}") public Employee getEmpByLastName(String name);
}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired EmployeeService employeeService; @RequestMapping("/emp/{id}") public Employee getEmployee(@PathVariable("id") Integer id){ Employee employee=employeeService.getEmp(id); return employee; } @GetMapping("/emp") public Employee updateEmp(Employee employee){ System.out.println("員工更新的方法調用"); Employee employee1 = employeeService.updateEmp(employee); return employee1; } @GetMapping("/delete") public String deleteEmp(Integer id){ System.out.println("刪除一個員工的相關信息"); return "刪除員工"; } @RequestMapping("/emps/{lastName}") public Employee getByLastName(@PathVariable("lastName") String lastName){ return employeeService.getEmployeeByLastName(lastName); }
}
應用類的配置 注意
下面是我最想寫的,當時看尚學堂的視頻一直寫不出來的,由于使用的版本不同,我使用的使用2.xxx
下面是我配置的RedisCacheManager
@Configuration
public class myredis {
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(ser)); RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(config).build(); return cacheManager;
}
} 這個寫法和1.xx明顯不同
下面是2.xx源碼
下面這副圖解釋這句
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(ser));
測試結果
到此,關于“SpringBoot如何使用Redis緩存”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。