springmvc集成使用redis过程

目录
  • Redis安装
  • spring集成redis
  • SpringMVC中使用redis
  • 写进和读取redis

Redis安装

首先安装redis。这个就不重点介绍了。windos下载redis就行。

我用的是mac

用命令行安装的。

安装命令

yum install redis 

运行命令

sudo redis-server

这样就安装运行成功了。

spring集成redis

首先你需要下载驱动包,下载 jedis.jar,确保下载最新驱动包。然后导包。

在spring配置文件里我这是ApplicationContext .xml文件添加

<!-- 引入同文件夹下的redis属性配置文件 -->
 <import resource="spring-redis.xml" />

然后用创建spring-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:context="http://www.springframework.org/schema/context"
       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.xsd">

	<!-- 缓存的层级-->
 	<context:component-scan base-package="com.niit.cache" />
	<!-- 引入redis配置 -->
 	<context:property-placeholder location="/WEB-INF/classes/redis.properties" ignore-unresolvable="true"/>

	<!-- Redis 配置 -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${redis.pool.maxTotal}" />
		<property name="maxIdle" value="${redis.pool.maxIdle}" />
		<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
	</bean>

	<!-- JedisCluster 集群高可用配置 -->
	<!--<bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
		<constructor-arg index="0">
			<set>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg index="0" value="${redis.ip1}" />
					<constructor-arg index="1" value="${redis.port1}" type="int" />
				</bean>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg index="0" value="${redis.ip2}" />
					<constructor-arg index="1" value="${redis.port2}" type="int" />
				</bean>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg index="0" value="${redis.ip3}" />
					<constructor-arg index="1" value="${redis.port3}" type="int" />
				</bean>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg index="0" value="${redis.ip4}" />
					<constructor-arg index="1" value="${redis.port4}" type="int" />
				</bean>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg index="0" value="${redis.ip5}" />
					<constructor-arg index="1" value="${redis.port5}" type="int" />
				</bean>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg index="0" value="${redis.ip6}" />
					<constructor-arg index="1" value="${redis.port6}" type="int" />
				</bean>
			</set>
		</constructor-arg>
		<constructor-arg index="1" value="2000" type="int"></constructor-arg>
		<constructor-arg index="2" value="100" type="int"></constructor-arg>
		<constructor-arg index="3" ref="jedisPoolConfig"></constructor-arg>
	</bean>-->

	<!--redis Sentinel主从高可用方案配置 -->
	<!-- <bean id="sentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
		<property name="master">
			<bean class="org.springframework.data.redis.connection.RedisNode">
				<property name="name" value="master-1"></property>
			</bean>
		</property>
		<property name="sentinels">
			<set>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="${sentinel1.ip}"></constructor-arg>
					<constructor-arg name="port" value="${sentinel1.port}"></constructor-arg>
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="${sentinel2.ip}"></constructor-arg>
					<constructor-arg name="port" value="${sentinel2.port}"></constructor-arg>
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="${sentinel3.ip}"></constructor-arg>
					<constructor-arg name="port" value="${sentinel3.port}"></constructor-arg>
				</bean>
			</set>
		</property>
	</bean>
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true">
		<property name="password" value="${redis.pass}" />
		<property name="poolConfig">
			<ref bean="jedisPoolConfig" />
		</property>
		<constructor-arg name="sentinelConfig" ref="sentinelConfiguration" />
	</bean> -->

	<!-- redis单节点数据库连接配置 -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis.ip}" />
		<property name="port" value="${redis.port}" />
		<property name="password" value="${redis.pass}" />
		<property name="poolConfig" ref="jedisPoolConfig" />
	</bean> 

	<!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
	</bean>

</beans>
public class RedisCache {
	public final static String CAHCENAME = "niitcache";// 缓存名
	public final static int CAHCETIME = 60;// 默认缓存时间 60S
	public final static int CAHCEHOUR = 60 * 60;// 默认缓存时间 1hr
	public final static int CAHCEDAY = 60 * 60 * 24;// 默认缓存时间 1Day
	public final static int CAHCEWEEK = 60 * 60 * 24 * 7;// 默认缓存时间 1week
	public final static int CAHCEMONTH = 60 * 60 * 24 * 7 * 30;// 默认缓存时间 1month

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	public <T> boolean putCache(String key, T obj) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.setNX(bkey, bvalue);
			}
		});
		return result;
	}

	public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
		redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				connection.setEx(bkey, expireTime, bvalue);
				return true;
			}
		});
	}

	public <T> boolean putListCache(String key, List<T> objList) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.setNX(bkey, bvalue);
			}
		});
		return result;
	}

	public <T> boolean putListCacheWithExpireTime(String key, List<T> objList, final long expireTime) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				connection.setEx(bkey, expireTime, bvalue);
				return true;
			}
		});
		return result;
	}

	public <T> T getCache(final String key, Class<T> targetClass) {
		byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.get(key.getBytes());
			}
		});
		if (result == null) {
			return null;
		}
		return ProtoStuffSerializerUtil.deserialize(result, targetClass);
	}

	public <T> List<T> getListCache(final String key, Class<T> targetClass) {
		byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.get(key.getBytes());
			}
		});
		if (result == null) {
			return null;
		}
		return ProtoStuffSerializerUtil.deserializeList(result, targetClass);
	}

	/**
	 * 精确删除key
	 *
	 * @param key
	 */
	public void deleteCache(String key) {
		redisTemplate.delete(key);
	}

	/**
	 * 模糊删除key
	 *
	 * @param pattern
	 */
	public void deleteCacheWithPattern(String pattern) {
		Set<String> keys = redisTemplate.keys(pattern);
		redisTemplate.delete(keys);
	}

	/**
	 * 清空所有缓存
	 */
	public void clearCache() {
		deleteCacheWithPattern(RedisCache.CAHCENAME + "|*");
	}
}

创建redis的配置文件 redis.properties。

写入

#redis config
redis.pass=
redis.pool.maxTotal=105
redis.pool.maxIdle=10
redis.pool.maxWaitMillis=5000
redis.pool.testOnBorrow=true

redis.ip=127.0.0.1
redis.port=6379

这些根据自己的需求自定义配置就好了

这样redis就继承好了

SpringMVC中使用redis

创建一个redisCache类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.niit.util.ProtoStuffSerializerUtil;
import java.util.List;
import java.util.Set;

/**
 * redis缓存
 *
 * @author James
 *
 */
@Component
public class RedisCache {

	public final static String CAHCENAME = "niitcache";// 缓存名
	public final static int CAHCETIME = 60;// 默认缓存时间 60S
	public final static int CAHCEHOUR = 60 * 60;// 默认缓存时间 1hr
	public final static int CAHCEDAY = 60 * 60 * 24;// 默认缓存时间 1Day
	public final static int CAHCEWEEK = 60 * 60 * 24 * 7;// 默认缓存时间 1week
	public final static int CAHCEMONTH = 60 * 60 * 24 * 7 * 30;// 默认缓存时间 1month

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	public <T> boolean putCache(String key, T obj) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.setNX(bkey, bvalue);
			}
		});
		return result;
	}

	public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
		redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				connection.setEx(bkey, expireTime, bvalue);
				return true;
			}
		});
	}

	public <T> boolean putListCache(String key, List<T> objList) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.setNX(bkey, bvalue);
			}
		});
		return result;
	}

	public <T> boolean putListCacheWithExpireTime(String key, List<T> objList, final long expireTime) {
		final byte[] bkey = key.getBytes();
		final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				connection.setEx(bkey, expireTime, bvalue);
				return true;
			}
		});
		return result;
	}

	public <T> T getCache(final String key, Class<T> targetClass) {
		byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.get(key.getBytes());
			}
		});
		if (result == null) {
			return null;
		}
		return ProtoStuffSerializerUtil.deserialize(result, targetClass);
	}

	public <T> List<T> getListCache(final String key, Class<T> targetClass) {
		byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.get(key.getBytes());
			}
		});
		if (result == null) {
			return null;
		}
		return ProtoStuffSerializerUtil.deserializeList(result, targetClass);
	}

	/**
	 * 精确删除key
	 *
	 * @param key
	 */
	public void deleteCache(String key) {
		redisTemplate.delete(key);
	}

	/**
	 * 模糊删除key
	 *
	 * @param pattern
	 */
	public void deleteCacheWithPattern(String pattern) {
		Set<String> keys = redisTemplate.keys(pattern);
		redisTemplate.delete(keys);
	}

	/**
	 * 清空所有缓存
	 */
	public void clearCache() {
		deleteCacheWithPattern(RedisCache.CAHCENAME + "|*");
	}
}

写进和读取redis

<span style="white-space:pre">  </span>String v = "test";
  cache.putCacheWithExpireTime("key", v, cache.CAHCEHOUR);
  String value = cache.getCache("key", String.class);
  System.out.println(value);

然后集成成功。redis是将数据放进内存里。所以需要考虑做redis服务器时候的内存性能,还有redis的缓存策略等等。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringMVC集成redis配置的多种实现方法

    第一步:下载并安装Redis(网上已经有很多安装教程在此不细讲了) 第二步:pom文件引入jar包 在此需要注意Redis和jedis连接工厂版本 redsi:https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis jedis:https://mvnrepository.com/artifact/redis.clients/jedis <!-- redis --> <dependency&

  • Springboot项目中使用redis的配置详解

    程序结构: 一.配置 1. 在pom.xml中添加依赖 pom.xml文件如下: <?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=&q

  • Spring基于注解整合Redis完整实例

    在<Redis之--Spring整合Redis>一文中,向大家介绍了如何将spring与Redis整合起来,但不是基于注解的形式,很多同学都希望能够通过注解的形式来简单的将Spring与Redis整合起来,这样,在使用的时候,只需要在相应的方法上加上注解,便可以使方法轻松的调用Redis的缓存.那么今天就来向大家介绍如何用基于注解的形式来整合Spring与Redis. 一.项目搭建 今天,我们不使用hibernate来操作数据库了,我们今天选择的框架是: Spring4(包括mvc.conte

  • springmvc集成使用redis过程

    目录 Redis安装 spring集成redis SpringMVC中使用redis 写进和读取redis Redis安装 首先安装redis.这个就不重点介绍了.windos下载redis就行. 我用的是mac 用命令行安装的. 安装命令 yum install redis 运行命令 sudo redis-server 这样就安装运行成功了. spring集成redis 首先你需要下载驱动包,下载 jedis.jar,确保下载最新驱动包.然后导包. 在spring配置文件里我这是Applica

  • SpringBoot 集成Redis 过程

    Redis 介绍: Redis 服务 Redis (REmote Dictionary Server) 是一个由Salvatore Sanfilippo 完成的key-value存储系统,是跨平台的非关系型数据库. Redis 是一个开源的使用ANSI C语言编写.遵循BSD 协议的.支持网络.可基于内存.分布式.可选择持久性的键值对存储数据库,并提供多语言的API. Redis 通常被认为是数据结构服务器,其值可以是字符串.哈希.列表.集合以及有序集合. Redis 优点 异常快,每秒可以执行

  • SpringBoot集成使用Redis及搭建过程

    目录 SpringBoot集成使用redis 搭建 1.导入jar包 2.配置连接redis 3.添加配置类RedisConfig 4.注入RedisTemplate 5.测试和使用 使用实例: SpringBoot集成使用redis Jedis 是 Redis 官方推出的一款面向 Java 的客户端,提供了很多接口供 Java 语言调用.可以在 Redis 官网下载. Spring-data-redis 是 spring 大家族的一部分,提供了在 srping 应用中通 过简单的配置访问 re

  • 基于Spring接口集成Caffeine+Redis两级缓存

    目录 前言 改造 JSR107 规范 Cache CacheManager 配置&使用 分布式环境改造 定义消息体 Redis消息配置 消息消费逻辑 修改DoubleCache 测试 总结 前言 在上一篇文章Redis+Caffeine两级缓存的实现中,我们介绍了3种整合Caffeine和Redis作为两级缓存使用的方法,虽然说能够实现功能,但实现手法还是太粗糙了,并且遗留了一些问题没有处理.本文将在上一篇的基础上,围绕两个方面进行进一步的改造: JSR107定义了缓存使用规范,spring中提

  • Java SSM框架(Spring+SpringMVC+MyBatis)搭建过程

    摘要: 这段时间搭建ssm环境,并测试几个下载的项目demo 安装相关文件: MyEclipse界面: 测试项目简单增删改: ssm+mysql+easyui项目: SSM+MYSQL+EXTJS项目 总结 以上所述是小编给大家介绍的Java SSM框架(Spring+SpringMVC+MyBatis)搭建过程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的.在此也非常感谢大家对我们网站的支持!

  • Springboot 集成 lombok.jar过程解析

    这篇文章主要介绍了Springboot 集成 lombok.jar过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 介绍 Spring Boot是非常高效的开发框架,lombok是一套代码模板解决方案,将极大提升开发的效率,这里介绍给大家使用. Lombok想要解决了的是在我们实体Bean中大量的Getter/Setter方法,以及toString, hashCode等可能不会用到,但是某些时候仍然需要复写,以期方便使用的方法:在使用Lo

  • SpringMVC实现Validation校验过程详解

    这篇文章主要介绍了SpringMVC实现Validation校验过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.概述 对前端的校验大多数通过js在页面校验,这种方法比较简单,如果对安全性考虑,还要在后台校验. springmvc使用JSR-303(javaEE6规范的一部分)校验规范,springmvc使用的是Hibernate Validator(和Hibernate的ORM) 二.步骤 2.1 引入 Hibernate Vali

  • SpringMVC RESTful支持实现过程演示

    这篇文章主要介绍了SpringMVC RESTful支持实现过程演示,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.概述 1.1 什么是RESTful RESTful软件开发理念,RESTful对http进行非常好的诠释. RESTful即Representational State Transfer的缩写. 综合上面的解释,我们总结一下什么是RESTful架构: 1)每一个URI代表一种资源: (2)客户端和服务器之间,传递这种资源的某种

  • Spring Boot整合Spring Cache及Redis过程解析

    这篇文章主要介绍了Spring Boot整合Spring Cache及Redis过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.安装redis a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址: https://github.com/MicrosoftArchive/redis/releases b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.wind

随机推荐