Spring MVC集成Redis

1:下载jar包 jedis-2.1.0.jar,spring-data-redis-1.0.2.RELEASE.jar, commons-pool2-2.2.jar

可在Maven仓库下载:https://mvnrepository.com/

 2:导入依赖

 3:添加配置  我的配置在 applicationContext.xml  db.properties

applicationContext.xml  配置文件加入

<!-- redis配置 -->
	<!-- redis配置文件 -->
	<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>
	<!-- redis连接池 -->
	<bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig"> 
		<property name="maxActive" value="${redis_max_active}"></property>
		<property name="maxIdle" value="${redis_max_idle}"></property>
		<property name="maxWait" value="${redis_max_wait}"></property>
		<property name="testOnBorrow" value="${redis_test_on_borrow}"></property>
	</bean>
	<!-- redis连接工厂 -->
	<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis_addr}"></property>
		<property name="port" value="${redis_port}"></property>
		<property name="password" value="${redis_auth}"></property>
		<property name="poolConfig" ref="jedisConfig"></property>
	</bean>
	<!-- redis操作模板,这里采用尽量面向对象的模板 -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
		<property name="connectionFactory" ref="connectionFactory" />
	<!--  	如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->
		<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>	

 db.properties 文件加入    (了解:如果集成了MySQL数据库  配置文件大致差不多)

# redis相关配置
#访问地址
redis_addr=localhost
#访问端口
redis_port=6379
#授权密码,有没有这一项取决于要连接的redis服务是否设置了此项
redis_auth=123456
#连接池的最大数据库连接数。设为0表示无限制
redis_max_active=1024
#最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis_max_idle=200
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis_max_wait=10000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis_test_on_borrow=true

4:最后测试一下

@Autowired
	private RedisTemplate redisTemplate;
	
	@Test
	public void test1() {
		redisTemplate.opsForValue().set("张三", "{‘hhh’:‘123456’}");
	}

通过redis可视化界面查看是否添加成功  如下图

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值