Spring MVC整合redis的配置
這個專案用到redis,所以學了一下怎樣在Spring框架下配置redis。
1、首先是在web.xml中新增Spring的配置檔案。
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>common design</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param>
<!-- 新增Spring mybatis的配置檔案 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,classpath*:mybatis-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
2、然後是redis的配置檔案(redis-config.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="true">
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- redis伺服器中心 -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig" />
<property name="port" value="${redis.port}" />
<property name="hostName" value="${redis.host}" />
<property name="password" value="${redis.password}" />
<property name="timeout" value="${redis.timeout}"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
<bean id="redisUtil" class="com.zkxl.fep.redis.RedisUtil">
<property name="redisTemplate" ref="redisTemplate" />
</bean>
</beans>
在Spring的配置檔案中引用redis的配置檔案
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="true">
<context:annotation-config/>
<context:component-scan base-package="com.test.fep" />
<!-- 增加redis的properties檔案 -->
<context:property-placeholder location="classpath*:jdbc.properties,classpath*:redis.properties" />
<import resource="datasource.xml"/>
<!-- 匯入redis的配置檔案 -->
<import resource="redis-config.xml"/>
</beans>
3、新建redis.properties,裡面包含redis連線需要的配置資訊
#redis setting
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
redis.maxIdle=100
redis.maxActive=300
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000
fep.local.cache.capacity =10000
一定要注意,每行後面千萬不要有空格,我就是因為這個問題卡了一兩個小時= =
4、編寫RedisUtil.java,裡面放有redis的增刪改查操作。
package com.test.fep.redis;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
public class RedisUtil {
private RedisTemplate<Serializable, Object> redisTemplate;
/**
* 批量刪除對應的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量刪除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 刪除對應的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判斷快取中是否有對應的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 讀取快取
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 寫入快取
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
logger.error("set cache error", e);
}
return result;
}
/**
* 寫入快取
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
logger.error("set cache error", e);
}
return result;
}
public long increment(final String key , long delta){
return redisTemplate.opsForValue().increment(key, delta);
}
public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
5、在功能程式碼中呼叫RedisUtil類中的方法,
package com.test.fep.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.fep.domain.SysAppLoginToken;
import com.test.fep.mapper.SysAppLoginTokenMapper;
import com.test.fep.redis.RedisUtil;
import com.test.fep.service.AuthService;
import net.sf.json.JSONObject;
@Service("authService")
public class AuthServiceImpl implements AuthService{
@Autowired
private SysAppLoginTokenMapper sysAppLoginTokenMapper ;
@Autowired
private RedisUtil redisUtil; //記得注入
@Override
public SysAppLoginToken verification(String tokenId) {
SysAppLoginToken token = null;
if (redisUtil.exists(tokenId)) {
token = (SysAppLoginToken) redisUtil.get(tokenId); //從快取中查詢token
}else{
token = sysAppLoginTokenMapper.selectByPrimaryKey(tokenId) ;
redisUtil.set(tokenId, token); //將token寫入快取
}
return null;
}
}
好了,到這裡就在一個專案中完整地使用了redis。
還需要注意的一點是,所有儲存在Redis中的介面都必須要實現Serializable介面。
轉自:https://www.cnblogs.com/cuglkb/p/6862609.html
另外一篇配置redis的文章:https://www.cnblogs.com/phil_jing/p/7468586.html
相關文章
- spring+redis的整合,使用spring-data-redis來整合SpringRedis
- Shiro和Spring MVC、Mybatis整合教程SpringMVCMyBatis
- Spring Boot + Mybatis + Spring MVC環境配置(四):MVC框架搭建Spring BootMyBatisMVC框架
- Spring Boot整合RedisSpring BootRedis
- Spring Boot 整合redisSpring BootRedis
- spring與redis整合SpringRedis
- Spring Boot + Mybatis + Spring MVC環境配置(三):DataSource配置Spring BootMyBatisMVC
- Spring MVC學習筆記和SSH的整合SpringMVC筆記
- Spring MVC 整合 Shiro 許可權控制SpringMVC
- Spring-Boot整合RedisSpringbootRedis
- spring boot(三)整合 redisSpring BootRedis
- IDEA配置SSM(Spring-Spring MVC-MyBatisIdeaSSMSpringMVCMyBatis
- Spring Boot + Mybatis + Spring MVC環境配置(二):Mybatis Generator配置Spring BootMyBatisMVC
- spring mvc專案配置一覽SpringMVC
- Spring Boot 專案整合RedisSpring BootRedis
- Spring Boot 如何快速整合 Redis 哨兵?Spring BootRedis
- Spring Boot系列筆記--整合RedisSpring Boot筆記Redis
- Spring Boot整合Redis實戰操作Spring BootRedis
- Spring Boot + Mybatis + Spring MVC環境配置(五):templates模板使用Spring BootMyBatisMVC
- Spring Boot整合Redis叢集(Cluster模式)Spring BootRedis模式
- 一文讀懂Spring整合RedisSpringRedis
- Spring security(四)-spring boot +spring security簡訊認證+redis整合Spring BootRedis
- spring - mvcSpringMVC
- spring、spring MVC、spring BootMVCSpring Boot
- 使用Spring Boot整合Apollo配置中心Spring Boot
- 手寫一個Redis和Spring整合的外掛RedisSpring
- tomcat + spring mvc原理外傳:spring mvc與前端的糾葛TomcatSpringMVC前端
- spring配置redis註解快取SpringRedis快取
- Spring 系列(二):Spring MVC的父子容器SpringMVC
- Spring Boot + Mybatis + Spring MVC環境配置(一) :Spring Boot初始化,依賴新增Spring BootMyBatisMVC
- 怎樣使用Spring Boot 整合配置 HTTPSSpring BootHTTP
- spring - mvc - @ScheduledSpringMVC
- spring - mvc - @ValidSpringMVC
- spring mvc interceptorsSpringMVC
- spring-mvc的工作原理SpringMVC
- Eclipse Spring MVC工程的建立EclipseSpringMVC
- 初識 SpringMVC,執行配置第一個Spring MVC 程式SpringMVC
- 非spring boot (即spring) 使用/整合 Spring cloud Config 分散式配置中心Spring BootCloud分散式