欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

ssm开发使用redis作为缓存的使用步骤

时间:2021-03-24 10:28:36|栏目:JAVA代码|点击:

1、关于spring配置文件中对于redis的配置

<!-- redis配置 -->
 <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  <!-- <property name="maxActive" value="90"/> -->
  <property name="maxIdle" value="5"/>
  <!-- <property name="maxWait" value="1000"/> -->
  <property name="testOnBorrow" value="true"/>
 </bean>
    <!--配置redis数据源-->
 <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
  <constructor-arg ref="jedisPoolConfig"/>
  <constructor-arg value="192.168.21.195"/>
  <constructor-arg value="6379"/>
 </bean>
    <!--配置自定义的RedisAPI工具类-->
 <bean id="redisAPI" class="org.slsale.common.RedisAPI">
  <property name="jedisPool" ref="jedisPool"/>
 </bean>

2、配置自定义的RedisAPI,对redis数据库的管理

package org.slsale.common;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * jedisAPI
 * @author luzhewu
 *
 */
public class RedisAPI {
 public JedisPool jedisPool;// redis连接池对象

 public JedisPool getJedisPool() {
  return jedisPool;
 }

 public void setJedisPool(JedisPool jedisPool) {
  this.jedisPool = jedisPool;
 }

 /**
  * set key and value tp redis
  * @param key
  * @param value
  * @return
  */
 public boolean set(String key, String value) {
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();// 获取jedis对象
   jedis.set(key, value);
   return true;
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   // 返还到连接池
   returnResource(jedisPool, jedis);
  }
  return false;
 }

 /**
  * 判断某个key是否存在
  * @param key
  * @return
  */
 public boolean exist(String key) {
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   return jedis.exists(key);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   // 返还到连接池
   returnResource(jedisPool, jedis);
  }
  return false;
 }

 /**
  * 通过key获取value
  * @param key
  * @return
  */
 public String get(String key) {
  String value = null;
  Jedis jedis = null;
  try {
   jedis = jedisPool.getResource();
   value = jedis.get(key);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   // 返还到连接池
   returnResource(jedisPool, jedis);
  }
  return value;
 }

 /**
  * 返还到连接池
  * @param jedisPool
  * @param jedis
  */
 public static void returnResource(JedisPool jedisPool, Jedis jedis) {
  if (jedis != null) {
   jedisPool.returnResource(jedis);
  }
 }
}

3、redis相关依赖

<!-- redis相关依赖jedis -->
   <dependency>
 <groupId>redis.clients</groupId>
 <artifactId>jedis</artifactId>
 <version>2.6.1</version>

上一篇:Hibernate一级缓存和二级缓存详解

栏    目:JAVA代码

下一篇:spring cloud 之 客户端负载均衡Ribbon深入理解

本文标题:ssm开发使用redis作为缓存的使用步骤

本文地址:http://www.codeinn.net/misctech/86770.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有