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 = "https://www.cnblogs.com/{id}")
public Person selectPerson(@PathVariable String id){
return personService.selectPerson(id);
}
@RequestMapping(value = "https://www.cnblogs.com/update")
public String updatePerson(@RequestBody Person person){
personService.updatePerson(person);
return "success";
}
@RequestMapping(value = "https://www.cnblogs.com/delete/{id}")
public String deletePerson(@PathVariable String id){
personService.deletePerson(id);
return "delete success";
}
}
??啟動專案,多次訪問http://localhost:8080/user/1 第一次時控制臺會出現select資訊,代表對資料庫進行了查詢操作,后面再訪問時則不會出現提示,表示沒有對資料庫執行操作,而是使用 Redis中的快取資料,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/501702.html
標籤:其他
