说明
要启用缓存支持,只需要 @EnableCaching 注释,Spring 引导就会自动配置缓存基础设施
例
pom.xml(只粘贴部分内容)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
文件结构
src/
+- main/
+- java/
+- com/
+- lee/
+- springbootdemo/
+- pojo/
+- City.java
+- repository/
+- CityRepository.java
+- service/
+- impl/
+- CityServiceImpl.java
+- CityService.java
+- controller/
+- CityRestController.java
+- SpringBootDemoApplication.java
+- resources/
+- <other resource>
City.java
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
}
CityRepository.java
public interface CityRepository extends JpaRepository<City, Long> {}
CityServiceImpl.java
@Service
public class CityServiceImpl implements CityService {
@Autowired
private CityRepository cityRepository;
@Override
public City save(City city) { return cityRepository.save(city); }
@Cacheable("cityCache")
@Override
public Optional<City> findById(Long id) { return cityRepository.findById(id); }
@Override
public void delete(Long id) { cityRepository.deleteById(id); }
}
CityRestController.java
@RestController
@RequestMapping("/city")
public class CityRestController {
@Autowired
private CityService cityService;
@GetMapping("/{name}/{state}")
public City city(@PathVariable String name, @PathVariable String state) {
City city = new City();
city.setName(name);
city.setState(state);
city = cityService.save(city);
return cityService.findById(city.getId()).get();
}
}
运行应用程序,浏览器访问地址,如下图
SpringBootJpa.png
查看 Redis
cached.png第二次执行 keys * 命令时,出现新数据,说明缓存已经存储在 Redis 中
网友评论