springboot +mybatis+mysql+redis


一、准備工作

  • 進入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>
View Code
  • 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\
View Code

二、配置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>
View Code
    • 注意在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 }
View Code

四、配置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 }
View Code

五、在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    }
View Code

    除了上述使用方法參數作為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 
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM