一、准备工作
- 进入springboot的环境搭建页面https://start.spring.io/
- 输入需要集成的项目,例如集成springboot的web、redis、mysql、mybatis,如下图所示:
- 点击Generate Project 按钮,生成springboot的基础代码
- springboot 的pom.xml内容如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <parent> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-parent</artifactId> 8 <version>2.1.1.RELEASE</version> 9 <relativePath/> <!-- lookup parent from repository --> 10 </parent> 11 <groupId>com.example</groupId> 12 <artifactId>demo</artifactId> 13 <version>0.0.1-SNAPSHOT</version> 14 <name>demo</name> 15 <description>Demo project for Spring Boot</description> 16 17 <properties> 18 <java.version>1.8</java.version> 19 </properties> 20 21 <dependencies> 22 <dependency> 23 <groupId>org.springframework.boot</groupId> 24 <artifactId>spring-boot-starter-data-redis</artifactId> 25 </dependency> 26 <dependency> 27 <groupId>com.alibaba</groupId> 28 <artifactId>fastjson</artifactId> 29 <version>1.2.44</version> 30 </dependency> 31 <dependency> 32 <groupId>org.springframework.boot</groupId> 33 <artifactId>spring-boot-starter-web</artifactId> 34 </dependency> 35 <dependency> 36 <groupId>org.mybatis.spring.boot</groupId> 37 <artifactId>mybatis-spring-boot-starter</artifactId> 38 <version>1.3.2</version> 39 </dependency> 40 41 <dependency> 42 <groupId>mysql</groupId> 43 <artifactId>mysql-connector-java</artifactId> 44 <scope>runtime</scope> 45 </dependency> 46 <dependency> 47 <groupId>org.springframework.boot</groupId> 48 <artifactId>spring-boot-starter-test</artifactId> 49 <scope>test</scope> 50 </dependency> 51 </dependencies> 52 53 <build> 54 55 <!-- 打包包含哪些静态文件 --> 56 <resources> 57 <resource> 58 <directory>src/main/resources</directory> 59 <includes> 60 <include>**/**</include> 61 </includes> 62 <filtering>false</filtering> 63 </resource> 64 <resource> 65 <directory>src/main/java</directory> 66 <includes> 67 <include>**/*.properties</include> 68 <include>**/*.xml</include> 69 </includes> 70 <filtering>false</filtering> 71 </resource> 72 </resources> 73 <plugins> 74 <plugin> 75 <groupId>org.springframework.boot</groupId> 76 <artifactId>spring-boot-maven-plugin</artifactId> 77 </plugin> 78 <!-- 打包是不执行测试方法 --> 79 <plugin> 80 <groupId>org.apache.maven.plugins</groupId> 81 <artifactId>maven-surefire-plugin</artifactId> 82 <configuration> 83 <skipTests>true</skipTests> 84 </configuration> 85 </plugin> 86 <!-- 打源码包 --> 87 <plugin> 88 <artifactId>maven-source-plugin</artifactId> 89 <configuration> 90 <attach>true</attach> 91 </configuration> 92 <executions> 93 <execution> 94 <phase>compile</phase> 95 <goals> 96 <goal>jar</goal> 97 </goals> 98 </execution> 99 </executions> 100 </plugin> 101 <!-- war包名称 --> 102 <plugin> 103 <groupId>org.apache.maven.plugins</groupId> 104 <artifactId>maven-war-plugin</artifactId> 105 <configuration> 106 <warSourceExcludes>src/main/resources/**</warSourceExcludes> 107 <warName>yakult</warName> 108 </configuration> 109 </plugin> 110 <!--编译标准 --> 111 <plugin> 112 <groupId>org.apache.maven.plugins</groupId> 113 <artifactId>maven-compiler-plugin</artifactId> 114 <configuration> 115 <source>1.8</source> 116 <target>1.8</target> 117 </configuration> 118 </plugin> 119 <plugin> 120 <groupId>org.springframework.boot</groupId> 121 <artifactId>spring-boot-maven-plugin</artifactId> 122 </plugin> 123 <plugin> 124 <groupId>org.mybatis.generator</groupId> 125 <artifactId>mybatis-generator-maven-plugin</artifactId> 126 <version>1.3.2</version> 127 <configuration> 128 <verbose>true</verbose> 129 <overwrite>true</overwrite> 130 <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> 131 </configuration> 132 </plugin> 133 </plugins> 134 </build> 135 </project>
- springboot的配置文件application.yml如下:
1 server: 2 port: 8080 3 servlet: 4 context-path: / 5 spring: 6 application: 7 name: yakult 8 datasource: 9 url: jdbc:mysql://192.168.0.116:3306/hb_dev?characterEncoding=utf8&useLegacyDatetimeCode=false&serverTimezone=UTC 10 username: root 11 password: 123456 12 driver-class-name: com.mysql.cj.jdbc.Driver 13 redis: 14 host: 192.168.0.116 15 port: 6379 16 password: flzx3QC 17 timeout: 1800 18 freemarker: 19 allow-request-override: false 20 cache: true 21 check-template-location: true 22 charset: UTF-8 23 content-type: text/html; charset=utf-8 24 expose-request-attributes: false 25 expose-session-attributes: false 26 expose-spring-macro-helpers: false 27 resources: 28 static-locations: classpath:/static/ 29 logging: 30 level: 31 root: error 32 path: D:\workspace\
二、配置mybatis自动生成代码
- 在src/main/resources文件下新建generatorConfig.xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 6 <generatorConfiguration> 7 <classPathEntry location="D:\maven\repos\mysql\mysql-connector-java\5.1.21\mysql-connector-java-5.1.21.jar" /> 8 9 <context id="Mysql2Tables" targetRuntime="MyBatis3"> 10 11 <!-- 是否去除自动生成的注释true:是 false:否 --> 12 <commentGenerator> 13 <property name="suppressDate" value="true"/> 14 <property name="suppressAllComments" value="true" /> 15 </commentGenerator> 16 17 <!-- 链接信息 --> 18 <jdbcConnection driverClass="com.mysql.jdbc.Driver" 19 connectionURL="jdbc:mysql://192.168.0.116:3306/hb_dev?characterEncoding=utf8" userId="root" password="123456"> <!-- db--> 20 </jdbcConnection> 21 22 <!-- 默认为false 把JDBC DECIMAL 和NUMERIC 类型解析为Integer, 23 为true 时把JDBC DECIMAL和NUMERIC 类型解析为java.math.BigDecimal --> 24 <javaTypeResolver > 25 <property name="forceBigDecimals" value="false" /> 26 <property name="" value=""/> 27 </javaTypeResolver> 28 29 <!-- targetProject:生成PO类的位置 --> 30 <!-- 是否让schema作为包的后缀 --> 31 <!-- 从数据库返回的值被清理前后的空格 --> 32 <javaModelGenerator targetPackage="com.jorudan.yakult.entity" targetProject="src/main/java"> <!-- domain--> 33 <property name="enableSubPackages" value="false" /> 34 <property name="trimStrings" value="true" /> 35 </javaModelGenerator> 36 37 <!-- targetProject:mapper映射文件生成的位置 --> 38 <!-- 是否让schema作为包的后缀 --> 39 <sqlMapGenerator targetPackage="com.jorudan.yakult.mapper" targetProject="src/main/java"> <!-- dao mapper--> 40 <property name="enableSubPackages" value="false" /> 41 </sqlMapGenerator> 42 43 <!-- targetPackage:mapper接口生成的位置 --> 44 <!-- 是否让schema作为包的后缀 --> 45 <javaClientGenerator type="XMLMAPPER" targetPackage="com.jorudan.yakult.mapper" targetProject="src/main/java"> <!-- dao --> 46 <property name="enableSubPackages" value="false" /> 47 </javaClientGenerator> 48 <!-- 指定数据库表 --> 49 <table tableName="data_pos_info" 50 enableCountByExample="false" 51 enableUpdateByExample="false" 52 enableDeleteByExample="false" 53 enableSelectByExample="false" 54 selectByExampleQueryId="false"> 55 </table> 56 57 </context> 58 </generatorConfiguration>
-
- 注意在pom.xml中对generatorConfig.xml的相关配置
- 执行生成代码命令
mybatis-generator:generate
三、配置mysql的配置类
- 在com.example.config包中新建MyBatisConfig类
1 @Configuration 2 @MapperScan("com.example.mapper") 3 public class MyBatisConfig { 4 5 }
四、配置redis的配置类
在com.example.conf包中新建RedisConfig的配置类
1 @Configuration 2 @EnableCaching 3 public class RedisConfig extends CachingConfigurerSupport{ 4 5 @Bean 6 public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { 7 CacheManager cacheManager = new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), 8 this.getRedisCacheConfigurationWithTtl(30*60),//设置默认名称保存在redis的缓存时间 9 this.getRedisCacheConfigurationMap());//设置详细的名称的缓存保存在redis的缓存时间 10 return cacheManager; 11 } 12 13 private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() { 14 Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(); 15 //SsoCache和BasicDataCache进行过期时间配置 16 redisCacheConfigurationMap.put("SsoCache", this.getRedisCacheConfigurationWithTtl(24*60*60)); 17 redisCacheConfigurationMap.put("BasicDataCache", this.getRedisCacheConfigurationWithTtl(30*60)); 18 return redisCacheConfigurationMap; 19 } 20 21 private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { 22 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); 23 ObjectMapper om = new ObjectMapper(); 24 om.setVisibility(PropertyAccessor.ALL, Visibility.ANY); 25 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 26 jackson2JsonRedisSerializer.setObjectMapper(om); 27 28 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); 29 redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( 30 RedisSerializationContext 31 .SerializationPair 32 .fromSerializer(jackson2JsonRedisSerializer) 33 ).entryTtl(Duration.ofSeconds(seconds)); 34 35 return redisCacheConfiguration; 36 } 37 38 }
五、在servier层的引用方式
@Cacheable(value="example",key="#userId") public List<DataPosInfo> getDataPosInfo(String userId) { System.out.println("--------------------------------------------------"); List<DataPosInfo> list = new ArrayList<>(); list.add(new DataPosInfo()); return list; }
六、关于三个注解@Cacheable、@CacheEvict、@CachePut、@CacheConfig的使用
- Cacheable的使用
-
@Cacheable可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。
如果一个方法上添加了@Cacheable标记,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。
缓存是以键值对进行的,值就是方法的返回结果,至于键的话,Spring又支持两种策略,默认策略和自定义策略,需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的。
@Cacheable
可以指定三个属性,value、key和conditionvalue
必须指定,表示当前方法的返回值会被缓存在哪个Cache上,对应Cache的名称。可以是一个Cache也可以是多个Cache,当需要指定多个Cache时其是一个数组。
-
@Cacheable("cache1")//Cache是发生在cache1上的 public User find(Integer id) { returnnull; } @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的 public User find(Integer id) { returnnull; }
用来指定Spring缓存时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。
自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使#参数名或者#p参数index。下面是几个使用参数作为key的示例。
1 // 如果要用固定字符串加上参数的属性记得加单引号 2 @Cacheable(value="users", key="'helloworld'+#p0.id") 3 public User find(User user) { 4 returnnull; 5 } 6 7 @Cacheable(value="users", key="#id") 8 public User find(Integer id) { 9 returnnull; 10 } 11 12 @Cacheable(value="users", key="#p0") 13 public User find(Integer id) { 14 returnnull; 15 } 16 17 @Cacheable(value="users", key="#user.id") 18 public User find(User user) { 19 returnnull; 20 } 21 22 @Cacheable(value="users", key="#p0.id") 23 public User find(User user) { 24 returnnull; 25 }
除了上述使用方法参数作为key之外,Spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息
有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过SpringEL表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次判断。如下示例表示只有当user的id为偶数时才会进行缓存。
@Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0") public User find(User user) { System.out.println("find user by user " + user); return user; }
- @CacheEvict的使用
- 这个注解用来清除缓存,在注解里面指定cachename,key和condition,spring会把符合这三个要求的额缓存删掉
- 总共有5个属性:value,key,condition,allentries,beforeInvocation
allentries
缺省为false
,将这个属性设置为true
的话就不用设置key了,会删除value指定的cachename下所有的缓存- beforeInvocation缺省为
false
,默认spring是会在调用方法成功之后清除缓存的,如果方法里面抛错了自然也就不清除了,但是把此值设置为true
的话spring会在调用方法前就删除缓存,也就是说不管方法执行结果如何缓存都删。
@CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 缓存 public void updateAccount(Account account) { updateDB(account); } @CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 缓存 public void reload() { reloadAll() }
- @CachePut
-
这个注解容易与@Cacheable搞混,对于@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。
@CachePut也可以声明一个方法支持缓存功能。不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
-
综合实例
//@Cacheable 在执行方法之前判断condition,如果返回true,则查缓存; @Cacheable(value = "user", key = "#id", condition = "#id lt 10") public User conditionFindById(final Long id) {} //@CachePut 在执行完方法后判断condition,如果返回true,则放入缓存; @CachePut(value = "user", key = "#id", condition = "#result.username ne 'zhang'") public User conditionSave(final User user) {} //@CachePut将在执行完方法后判断unless,如果返回false,则放入缓存;(即跟condition相反) @CachePut(value = "user", key = "#user.id", unless = "#result.username eq 'zhang'") public User conditionSave2(final User user) {} //@CacheEvict, beforeInvocation=false表示在方法执行之后调用,判断condition,如果返回true,则移除缓存; @CacheEvict(value = "user", key = "#user.id", beforeInvocation = false, condition = "#result.username ne 'zhang'") public User conditionDelete(final User user) {} --------------------- 作者:hugeo-coala 来源:CSDN 原文:https://blog.csdn.net/u010588262/article/details/81003493 版权声明:本文为博主原创文章,转载请附上博文链接!