pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>

application.properties

#
server.address=0.0.0.0
server.port=8080
server.servlet.context-path=/test
server.session.timeout=300
server.error.path=/error
#
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.buffered=true
server.tomcat.accesslog.directory=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/logs
#
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
#
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true file.upload.path=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/fileUpLoad spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/temp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=gis
spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver ##Druid
spring.datasource.druid.one.initial-size=2
spring.datasource.druid.one.max-active=5
spring.datasource.druid.one.min-idle=1
spring.datasource.druid.one.max-wait=60000
spring.datasource.druid.one.pool-prepared-statements=true
spring.datasource.druid.one.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.one.validation-query-timeout=60000
spring.datasource.druid.one.test-on-borrow=false
spring.datasource.druid.one.test-on-return=false
spring.datasource.druid.one.test-while-idle=true
spring.datasource.druid.one.time-between-eviction-runs-millis=60000
spring.datasource.druid.one.min-evictable-idle-time-millis=100000
#spring.datasource.druid.one.max-evictable-idle-time-millis=
spring.datasource.druid.one.filters=stat,wall,log
spring.datasource.druid.one.logSlowSql=true #
# debug=true # Enable debug logs.
# trace=true # Enable trace logs. # LOGGING
logging.config=classpath:logback.xml spring.redis.host=127.0.0.1
spring.redis.password=gis
spring.redis.port=6379
spring.redis.pool.max-active=8
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
spring.redis.ssl=false
spring.redis.timeout=5000 redis.message.topic=spring.news.* # Cache
spring.cache.type=Redis
spring.cache.redis.cache-null-values=true
spring.cache.redis.key-prefix=spring:cache:
spring.cache.redis.time-to-live=0ms
spring.cache.redis.use-key-prefix=true

启动类

package com.smartmap.sample.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableCaching
@EnableTransactionManagement
@SpringBootApplication
public class TestCacheApplication { public static void main(String[] args) {
SpringApplication.run(TestCacheApplication.class, args); } }

配置类

package com.smartmap.sample.test.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class RedisCacheManagerCustomizer { @Value("${spring.cache.redis.key-prefix}")
private String keyPrefix; @Bean
public RedisCacheConfiguration redisCacheConfiguration() {
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
return RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer))
.prefixKeysWith(keyPrefix);
} /*@Bean
public RedisCacheManager getRedisCacheManager(RedisConnectionFactory connectionFactory) { RedisCacheManagerBuilder redisCacheManagerBuilder = RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
// Key
RedisSerializer<String> redisSerializerKey = new StringRedisSerializer();
SerializationPair<String> serializationPairKey = SerializationPair.fromSerializer(redisSerializerKey);
// Value
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(
objectMapper);
//RedisSerializer<Object> redisSerializerValue = jackson2JsonRedisSerializer;
//
RedisSerializer<Object> redisSerializerValue = genericJackson2JsonRedisSerializer;
//
SerializationPair<Object> serializationPairValue = SerializationPair.fromSerializer(redisSerializerValue);
//RedisSerializationContext.SerializationPair<Object> serializationPairValue = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializerValue); //
redisCacheConfiguration.serializeKeysWith(serializationPairKey);
redisCacheConfiguration.serializeValuesWith(serializationPairValue);
redisCacheManagerBuilder.cacheDefaults(redisCacheConfiguration);
RedisCacheManager redisCacheManager = redisCacheManagerBuilder.build(); //
return redisCacheManager;
}*/ }

实体类 Menu

package com.smartmap.sample.test.entity;

public class Menu {
Long id;
String code;
String name;
Long parentId; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Long getParentId() {
return parentId;
} public void setParentId(Long parentId) {
this.parentId = parentId;
}
}

实体类 MenuNode

package com.smartmap.sample.test.entity;

import java.util.ArrayList;
import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; public class MenuNode {
private Menu menu;
private List<MenuNode> children = new ArrayList<MenuNode>();
@JsonIgnore
private MenuNode parent; public Menu getMenu() {
return menu;
} public void setMenu(Menu menu) {
this.menu = menu;
} public List<MenuNode> getChildren() {
return children;
} public void setChildren(List<MenuNode> children) {
this.children = children;
} public MenuNode getParent() {
return parent;
} public void setParent(MenuNode parent) {
this.parent = parent;
} }

缓存应用

package com.smartmap.sample.test.service.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service; import com.smartmap.sample.test.entity.Menu;
import com.smartmap.sample.test.entity.MenuNode;
import com.smartmap.sample.test.service.MenuService; @Service
public class MenuServiceImpl implements MenuService {
Log log = LogFactory.getLog(this.getClass()); /**
* 清除缓存
*/
@CacheEvict(cacheNames = { "menu", "menuTree" }, allEntries = true)
public void addMenu(Menu menu) { } /**
* 添加缓存(含条件), 注意key中的是Spring EL表达式
*/
@Cacheable(cacheNames = "menu", key = "'menu:' + {#id}", condition = "#id > 0")
public Menu getMenu(Long id) {
log.info("call service getMenu " + id);
// 模拟
Menu menu = new Menu();
menu.setCode("test");
menu.setId(id);
menu.setName("菜单" + id);
menu.setParentId(1l); return menu;
} /**
* 添加缓存
*/
@Cacheable(cacheNames = "menuTree", key = "'menuTree'")
public MenuNode getMenuTree() { log.info("call menu tree ");
Menu root = new Menu();
root.setCode("root");
root.setId(1l);
root.setName("系统管理");
root.setParentId(null); Menu menu = new Menu();
menu.setCode("menu");
menu.setId(1l);
menu.setName("菜单管理");
menu.setParentId(1l); MenuNode tree = new MenuNode();
tree.setMenu(root);
tree.setParent(null); MenuNode menuTree = new MenuNode();
menuTree.setMenu(menu);
menuTree.setParent(tree);
tree.getChildren().add(menuTree); return tree; } /**
* 更新缓存
*/
@CachePut
(cacheNames = "menu", key = "'menu:' + {#menu.id}")
public Menu update(Menu menu) {
return menu;
} /**
* 组合处理多种缓存
*
* @param menu
*/
@Caching
(evict = { @CacheEvict(cacheNames = { "menu" }, allEntries = true),
@CacheEvict(cacheNames = { "menuTree" }, allEntries = true) })
public void updateCascading(Menu menu) { }
}

Controller类

package com.smartmap.sample.test.controller.rest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.smartmap.sample.test.entity.Menu;
import com.smartmap.sample.test.entity.MenuNode;
import com.smartmap.sample.test.service.MenuService; @RestController
@RequestMapping("/api/v1.1/system/menu")
public class MenuController {
private final Log logger = LogFactory.getLog(MenuController.class); @Autowired
MenuService menuService; /**
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/menu/'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "id":123, "code":"menuCode1", "name":"123" }'
*
* @return
* @throws Exception
*/
@PostMapping("/")
public String addMenu(@RequestBody Menu menu) throws Exception{
menuService.addMenu(menu);
//模拟改变缓存
return "{\"success\":true}";
} /**
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/menu/123'
*
* @param menuId
* @return
* @throws Exception
*/
@GetMapping("/{menuId}")
public Menu getMenu(@PathVariable("menuId") Long menuId) throws Exception{
return menuService.getMenu(menuId);
} /**
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/menu/tree'
*
* @return
* @throws Exception
*/
@GetMapping("/tree")
public MenuNode getMenuTree() throws Exception{
return menuService.getMenuTree();
} }

Spring Boot—19Cache的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  4. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  7. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  8. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  9. 玩转spring boot——结合jQuery和AngularJs

    在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

随机推荐

  1. 如何让IE 低版本下支持 css3属性

    依赖源  该文件为  ie-css3.htc    (特别提示.htc为二进制文件,只会在ie中识别,让IE浏览器支持CSS3的一些属性) 以下为依赖文件源码 通过源码我们可以看到 该文件在一定程度上 ...

  2. HttpContext rewritePath后中文乱码

    文章为转载 由于种种原因,最近将服务器上部署的网站修改4.0框架.但悲剧的问题出现了,发现搜索中文的时候关键词都成乱码了. 在网上查找相关资料得到几种相关解决方案如下: 服务器打补丁server200 ...

  3. 关于JSON基础的总结

    本文总结自百度百科 JSON 语法规则 JSON 语法是 JavaScript 对象表示语法的子集. 数据在键值对中 数据由逗号分隔 花括号保存对象 方括号保存数组 JSON 名称/值对 JSON 数 ...

  4. IDEA里运行程序时出现Error:scalac:error while loading JUnit4 , Scala signature JUnit4 has wrong version错误的解决办法(图文详解)

    不多说,直接上干货! 问题详情 当我们在运行程序时,出现Error:scalac:error while loading JUnit4 , Scala signature JUnit4 has wro ...

  5. 解决ssh登陆超时方案

    ssh登陆一般默认3分钟无操作则断开连接,有时候还是很烦的,于是解决这个问题. sudo修改/etc/ssh/sshd_conf文件 #sudo vim /etc/ssh/sshd_config #在 ...

  6. tomcat启动(Ⅷ)--请求最终目的地 getContainer().getPipeline().getFirst().invoke(request, response)

    当tomcat的Conector保存着StandardService实例,而StandardService保存着Container的实例 当Http11NioProcessor.process()方法 ...

  7. Vue前端框架面试问题

    1.active-class是哪个组件的属性?嵌套路由怎么定义? 答:vue-router模块的router-link组件. 2.怎么定义vue-router的动态路由?怎么获取传过来的动态参数? 答 ...

  8. XML 实体

    实体可以简单的理解为引用数据项的方法,可以是普通的文本也可以是二进制数据. 实体可以分为通用实体和参数实体.通用实体用于XML当中,用于引用文本或者二进制数据,而参数实体只能在DTD中使用.通用实体与 ...

  9. Aviator 表达式求值引擎开源框架

    简介¶ Aviator是一个高性能.轻量级的java语言实现的表达式求值引擎,主要用于各种表达式的动态求值.现在已经有很多开源可用的java表达式求值引擎,为什么还需要Avaitor呢? Aviato ...

  10. ABP学习入门系列(一)(第一个ABP项目)

    ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称.ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应用程序的新起点,它 ...