最近在學習redis,雖然現在還不是很熟練。不過可以進行簡單的框架整合開發。
IDE:我使用的是IDEA。springmvc+spring+mybatis的整合這個我就不多說了,下面我們先進行這塊的整合,最后在加入redis。下邊這塊就直接上代碼。
源碼:https://gitee.com/smfx1314/springmvcredis.git
首先看一下我的工程結構:
第一步:在pox.xml中引入jar
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jiangfx</groupId> <artifactId>springmvc-redis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc-redis Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build> </project>
第二步:配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 配置spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 編碼過濾器 --> <filter> <filter-name>charsetEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>charsetEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置springmvc --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern><!-- 攔截所有請求 --> </servlet-mapping> </web-app>
第三步:配置springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置自動掃描的包 --> <context:component-scan base-package="com.jiangfx.controller"/> <!-- 配置靜態資源文件 --> <mvc:default-servlet-handler/> <!-- 開啟注解模式 --> <mvc:annotation-driven/> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp"></property><!-- 視圖路徑 --> <property name="suffix" value=".jsp"></property><!-- 視圖后綴名 --> </bean> </beans>
第四步:配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 配置掃描的包 --> <context:component-scan base-package="com.jiangfx.service"/> <!-- 配置數據庫 --> <!-- 加載配置文件 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springredis"></property> <property name="user" value="root"></property> <property name="password" value="1234"></property> </bean> <!-- 配置sqlSessionFactory, 並將數據源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入數據源 --> <property name="dataSource" ref="dataSource"></property> <!--載入mybatis配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--載入配置mapper映射的xml--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 配置映射接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.jiangfx.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置聲明式事務 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
實體類:entity。一定要實現序列化接口,不然redis沒法對其操作
package com.jiangfx.entity; import java.io.Serializable; /** * Created by jiangfeixiang on 2018/4/27 */ public class User implements Serializable { private Integer id; private String username; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + '}'; } }
第五步:Mapper層
編寫UserMapper接口
package com.jiangfx.mapper; import com.jiangfx.entity.User; import java.util.List; /** * Created by jiangfeixiang on 2018/4/27 */ public interface UserMapper { /** * 查詢 * @return */ List<User> getAll(); /** * 插入 * @param user */ void insertUser(User user); }
之后我們編寫對應的UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jiangfx.mapper.UserMapper"> <!-- 查詢 --> <select id="getAll" resultType="User"> select * from user </select> <!--插入--> <insert id="insertUser" parameterType="User"> insert into user(id,username) VALUES (#{id},#{username}) </insert> </mapper>
第六步:service層
首先是UserService接口
package com.jiangfx.service; import com.jiangfx.entity.User; import java.util.List; /** * Created by jiangfeixiang on 2018/4/27 */ public interface UserService { /** * 查詢 * @return */ List<User> getAll(); /** * 插入 */ void insertUser(User user); }
然后是對應的實現類
package com.jiangfx.service.Impl; import com.jiangfx.entity.User; import com.jiangfx.mapper.UserMapper; import com.jiangfx.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by jiangfeixiang on 2018/4/27 */ @Service @Transactional public class UserServiceImpl implements UserService { //注入userMapper @Autowired private UserMapper userMapper; /** * 查詢所有 * 使用@Cacheable地很詭異緩存策略, * 當緩存中有值,則返回緩存數據,否則則訪問數據庫 * value引用緩存管理器,key定義緩存的鍵 * @return */ @Override // @Cacheable(value = "redisCacheManager",key = "'getAll'") public List<User> getAll() { List<User> userMapperAll = userMapper.getAll(); System.out.println("沒有走緩存就打印我..........."); return userMapperAll; } /** * 添加用戶 */ @Override // @CachePut(value = "redisCacheManager",key = "'insertUser'") public void insertUser(User user){ userMapper.insertUser(user); } }
第七部:controller層
UserController
package com.jiangfx.controller; import com.jiangfx.entity.User; import com.jiangfx.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; /** * Created by jiangfeixiang on 2018/4/27 */ @Controller public class UserController { //注入 @Autowired private UserService userService; /** * 查詢所有用戶 */ @RequestMapping(value = "/getAll",method = RequestMethod.GET) public String getAll(){ List<User> list = userService.getAll(); return "list"; } /** * 跳轉到添加頁面 */ @RequestMapping(value = "/insertUserPage",method = RequestMethod.GET) public String insertUserPage(){ return "save"; } /** * 插入 */ @RequestMapping(value = "/insertUser",method = RequestMethod.POST) public String insertUser(User user){ userService.insertUser(user); return "redirect:/getAll"; } }
JSP頁面很簡單,主要是為了測試用,一個歡迎頁index.jsp,一個添加用戶頁save.jsp,一個操作成功跳轉對應頁面的list.jsp
index.jsp
<a href="/getAll">查詢</a> <a href="/insertUserPage">添加</a>
save.jsp
<form action="/insertUser" method="post"> 姓名:<input type="text" name="username"> <input type="submit" value="提交"> </form>
list.jsp我就直接一句話,成功。你們看着寫。
之后啟動測試看看是否成功。當然,如果你安照我的寫,那么肯定不會錯的。
接下來我們開始配置redis。
首先加入jar包:
<!-- jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!-- spring-data-redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.2.RELEASE</version> </dependency>
然后:創建一個spring-data-redis.xml專門放置redis的配置,在來一個redis.properties屬性文件,放置redis的屬性配置。如下:
redis.properties
# Redis Setting # Redis默認有16個庫,序號是0-15,默認是選中的是0號數據庫 spring.redis.database=0 # Redis服務器地址 spring.redis.host=(你的地址) # Redis服務器連接端口,默認是6379 spring.redis.port=6379 # Redis服務器連接密碼(默認為空) spring.redis.password= # 連接池最大阻塞等待時間(使用負值表示沒有限制),根據實際情況修改 spring.redis.pool.maxWaitMillis=-1 # 連接池中的最大空閑連接,根據實際情況修改 spring.redis.pool.maxIdle=8 # 連接池中的最小空閑連接,根據實際情況修改 spring.redis.pool.minIdle=0 # 連接超時時間(毫秒),根據實際情況修改 spring.redis.timeout=2000
spring-data-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:redis="http://www.springframework.org/schema/redis" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 載入redis.properties,這里要特別注意,如果有多個properties文件,必須用逗號分開,不能寫成兩個 <context:property-placeholder/> -->
<context:property-placeholder location="classpath:redis.properties" />
<!-- 配置JedisPoolConfig連接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${spring.redis.pool.maxIdle}"></property>
<property name="minIdle" value="${spring.redis.pool.minIdle}"></property>
<property name="maxWaitMillis" value="${spring.redis.pool.maxWaitMillis}"></property>
</bean>
<!-- 配置jedis連接工廠 -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"></property>
<property name="hostName" value="${spring.redis.host}"></property>
<property name="port" value="${spring.redis.port}"></property>
<!--<property name="password" value="${spring.redis.password}"></property>-->
<property name="database" value="${spring.redis.database}"></property>
<property name="timeout" value="${spring.redis.timeout}"></property>
</bean>
<!-- 配置RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"></property>
<!--String-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
</property>
<!--hash-->
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
</bean>
<!--
定義緩存管理器redisCacheManager。
注意:cache-manager默認值是cacheManager,你的緩存管理器id要是命名是cacheManager,這里可以省略
-->
<!--1.使用注解驅動-->
<cache:annotation-driven cache-manager="redisCacheManager"></cache:annotation-driven>
<!--2.定義緩存管理器-->
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<!--通過構造方法注入redisTemplate-->
<constructor-arg index="0" ref="redisTemplate"></constructor-arg>
<!--定義超時時間,單位秒-->
<property name="defaultExpiration" value="5000"></property>
<!--設置緩存器名稱-->
<property name="cacheNames">
<list>
<value>redisCacheManager</value>
</list>
</property>
</bean>
</beans>
在applicationContext中引入redis的配置spring-data-redis.xml,當然你也可以配置在一起。
<!-- 引入spring-data-redis.xml --> <import resource="spring-data-redis.xml"/>
上面已經定義好緩存管理器了,下面我們就可以在serviceImpl中使用注解進行操作。如下:
在getAll查詢方法上添加(serviceImpl中注釋掉的那點)
@Cacheable(value = "redisCacheManager",key = "'getAll'")
在insertUser添加方法上加入(serviceImpl中注釋掉的那點)
@CachePut(value = "redisCacheManager",key = "'insertUser'")
注意:
value的值是你redis配置文件對應的緩存管理器的id值
key = "'insertUser'":是你要緩存到redis中的值,下次spring會直接通過key獲取結果。注意key的值中還有個單引號。
@Cacheable:適合查詢,有返回值的方法上。因為,每次請求在進入方法之前,spring會先從緩存服務器中查找對應的key,如果有,就直接返回。否則再去查詢數據庫,在將結果通過key保存到緩存中。
@CachePut:適合添加,修改,void方法上。因為spring不會事先去緩存服務器中查詢數據,而是直接執行方法,然后將結果通過key保存到緩存中。這樣是防止數據不一致。
以上都寫好后可以啟動服務器,然后運行。為了明顯,我在serviceImpl中查詢方法中有個輸出,你可以先注釋掉緩存注解運行,發現每次都會輸入。當你啟動注解時,沒有輸入。說明spring每次回自動到緩存中查找數據。如下:
(下面的測試你們可以不用理會,這個是我在搭建環境的時候測試是否搭建成功。我的邏輯可能不夠清晰,有問題可以聯系我)
測試
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.RedisTemplate; /** * Created by jiangfeixiang on 2018/4/26 */ public class SpringmvcRedisTest { private static ApplicationContext applicationContext; static{ applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); } @Test public void testApplicationContext(){ System.out.println("11111111111111111"+applicationContext); } @Test public void testRedisConnection(){ RedisTemplate redisTemplate = (RedisTemplate)applicationContext.getBean("redisTemplate"); redisTemplate.renameIfAbsent("k2", "k1");//如果key=k2存在,則將key修改為k1。前提是你的redis中得有k2。不然報錯。這不你也可以不寫。 System.out.println(redisTemplate); //這里有輸出也可以。 } }
以上測試這塊,你可以不用寫。
如何查看是否成功?我這里是通過可視化軟件:Redis Desktop Manager,你也可以直接在redis-cli客戶端查看
以上就是springmvc整合redis的過程,如果有什么問題都可以聯系我。