最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

redis與ssm整合方法(mybatis二級緩存)

 更新時(shí)間:2017年12月11日 08:58:07   作者:cui5445  
本文給大家介紹redis與ssm整合方法(mybatis二級緩存)。主要是利用redis去做mybatis的二級緩存,mybaits映射文件中所有的select都會(huì)刷新已有緩存,如果不存在就會(huì)新建緩存,所有的insert,update操作都會(huì)更新緩存

SSM+redis整合

ssm框架之前已經(jīng)搭建過了,這里不再做代碼復(fù)制工作。

這里主要是利用redis去做mybatis的二級緩存,mybaits映射文件中所有的select都會(huì)刷新已有緩存,如果不存在就會(huì)新建緩存,所有的insert,update操作都會(huì)更新緩存。

redis的好處也顯而易見,可以使系統(tǒng)的數(shù)據(jù)訪問性能更高。本節(jié)只是展示了整合方法和效果,后面會(huì)補(bǔ)齊redis集群、負(fù)載均衡和session共享的文章。

下面就開始整合工作:

后臺(tái)首先啟動(dòng)redis-server(后臺(tái)啟動(dòng)與遠(yuǎn)程連接linux服務(wù)的方法都需要改redis.conf文件),啟動(dòng)命令“./src/redis-server ./redis.conf”

我這里是windows系統(tǒng)下開發(fā)的,推薦一個(gè)可視化工具“Redis Desktop manager”,需要遠(yuǎn)程連接linux下的redis,需要linux下開啟端口對外開放(具體方法是修改/etc/sysconfig/iptables文件,增加對外端口開發(fā)命令)。

以上操作都完成后,即可遠(yuǎn)程連接成功了,如圖:

現(xiàn)在還沒有緩存記錄,下面進(jìn)入代碼階段,首先在pom.xml中增加需要的redis jar包

<dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.6.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.0</version>
    </dependency>
     <!-- 添加druid連接池包 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.24</version>
    </dependency>

pom.xml寫好后,還需要新增兩個(gè)配置文件:redis.properties

redis.host=192.168.0.109
redis.port=6379
redis.pass=123456
redis.maxIdle=200
redis.maxActive=1024
redis.maxWait=10000
redis.testOnBorrow=true

其中字段也都很好理解,再加入配置文件:spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:task="http://www.springframework.org/schema/task" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-4.3.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  <!-- 連接池基本參數(shù)配置,類似數(shù)據(jù)庫連接池 -->
   <context:property-placeholder location="classpath*:redis.properties" />
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxTotal" value="${redis.maxActive}"/>
    <property name="maxIdle" value="${redis.maxIdle}" />
    <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
  </bean>
  <!-- 連接池配置,類似數(shù)據(jù)庫連接池 -->
  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
    <property name="hostName" value="${redis.host}"></property>
    <property name="port" value="${redis.port}"></property>
    <property name="password" value="${redis.pass}"></property>
    <property name="poolConfig" ref="poolConfig"></property> 
  </bean>
  <!-- 調(diào)用連接池工廠配置 -->
  <!-- <bean id="redisTemplate" class=" org.springframework.data.redis.core.RedisTemplate">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory"></property>
    如果不配置Serializer,那么存儲(chǔ)的時(shí)候智能使用String,如果用User類型存儲(chǔ),那么會(huì)提示錯(cuò)誤User 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> -->
  <bean id="redisCacheTransfer" class="com.cjl.util.RedisCacheTransfer">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
  </bean>
</beans>

配置文件寫好后,就開始java代碼的編寫:

JedisClusterFactory.java

package com.cjl.util;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean {
  private Resource addressConfig;
  private String addressKeyPrefix;
  private JedisCluster jedisCluster;
  private Integer timeout;
  private Integer maxRedirections;
  private GenericObjectPoolConfig genericObjectPoolConfig;
  private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");
  public JedisCluster getObject() throws Exception {
    return jedisCluster;
  }
  public Class<? extends JedisCluster> getObjectType() {
    return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
  }
  public boolean isSingleton() {
    return true;
  }
  private Set<HostAndPort> parseHostAndPort() throws Exception {
    try {
      Properties prop = new Properties();
      prop.load(this.addressConfig.getInputStream());
      Set<HostAndPort> haps = new HashSet<HostAndPort>();
      for (Object key : prop.keySet()) {
        if (!((String) key).startsWith(addressKeyPrefix)) {
          continue;
        }
        String val = (String) prop.get(key);
        boolean isIpPort = p.matcher(val).matches();
        if (!isIpPort) {
          throw new IllegalArgumentException("ip 或 port 不合法");
        }
        String[] ipAndPort = val.split(":");
        HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
        haps.add(hap);
      }
      return haps;
    } catch (IllegalArgumentException ex) {
      throw ex;
    } catch (Exception ex) {
      throw new Exception("解析 jedis 配置文件失敗", ex);
    }
  }
  public void afterPropertiesSet() throws Exception {
    Set<HostAndPort> haps = this.parseHostAndPort();
    jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);
  }
  public void setAddressConfig(Resource addressConfig) {
    this.addressConfig = addressConfig;
  }
  public void setTimeout(int timeout) {
    this.timeout = timeout;
  }
  public void setMaxRedirections(int maxRedirections) {
    this.maxRedirections = maxRedirections;
  }
  public void setAddressKeyPrefix(String addressKeyPrefix) {
    this.addressKeyPrefix = addressKeyPrefix;
  }
  public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
    this.genericObjectPoolConfig = genericObjectPoolConfig;
  }
}

RedisCache.java

package com.cjl.util;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class RedisCache implements Cache {
  private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
  private static JedisConnectionFactory jedisConnectionFactory;
  private final String id;
  private final ReadWriteLock rwl = new ReentrantReadWriteLock();
  public RedisCache(final String id) {
    if (id == null) {
      throw new IllegalArgumentException("Cache instances require an ID");
    }
    logger.debug("MybatisRedisCache:id=" + id);
    this.id = id;
  }
  /**
   * 清空所有緩存
   */
  public void clear() {
    rwl.readLock().lock();
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      connection.flushDb();
      connection.flushAll();
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.readLock().unlock();
    }
  }
  public String getId() {
    return this.id;
  }
  /**
   * 獲取緩存總數(shù)量
   */
  public int getSize() {
    int result = 0;
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      result = Integer.valueOf(connection.dbSize().toString());
      logger.info("添加mybaits二級緩存數(shù)量:" + result);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
    }
    return result;
  }
  public void putObject(Object key, Object value) {
    rwl.writeLock().lock();
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
      connection.set(SerializeUtil.serialize(key), SerializeUtil.serialize(value));
      logger.info("添加mybaits二級緩存key=" + key + ",value=" + value);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.writeLock().unlock();
    }
  }
  public Object getObject(Object key) {
    // 先從緩存中去取數(shù)據(jù),先加上讀鎖
    rwl.readLock().lock();
    Object result = null;
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
      result = serializer.deserialize(connection.get(serializer.serialize(key)));
      logger.info("命中mybaits二級緩存,value=" + result);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.readLock().unlock();
    }
    return result;
  }
  public Object removeObject(Object key) {
    rwl.writeLock().lock();
    JedisConnection connection = null;
    Object result = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
      result = connection.expire(serializer.serialize(key), 0);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.writeLock().unlock();
    }
    return result;
  }
  public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
    RedisCache.jedisConnectionFactory = jedisConnectionFactory;
  }
  public ReadWriteLock getReadWriteLock() {
    // TODO Auto-generated method stub
    return rwl;
  }
}

RedisCacheTransfer.java

package com.cjl.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
/**
 * 靜態(tài)注入中間類
 */
public class RedisCacheTransfer {
   @Autowired
    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
      RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    }
}

SerializeUtil.java

package com.cjl.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * 
 * @author cjl
 *
 */
public class SerializeUtil {
  /**
   * 序列化
   */
  public static byte[] serialize(Object object) {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
      // 序列化
      baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      byte[] bytes = baos.toByteArray();
      return bytes;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   *反序列化
   */
  public static Object unserialize(byte[] bytes) {
    if (bytes !=null) {
      ByteArrayInputStream bais = null;
      try {
        // 反序列化
        bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return ois.readObject();
      } catch (Exception e) {
      }
    } 
    return null;
  }
}

所有東西準(zhǔn)備齊全后還需要修改映射文件

要使mybaits緩存生效,還需如上圖這樣開啟二級緩存。配置文件還需要在web.xml中加載生效

一切準(zhǔn)備就緒后,啟動(dòng)服務(wù)

啟動(dòng)成功后,點(diǎn)擊員工表單可以觸發(fā)查詢所有員工的方法,第一次進(jìn)行查詢語句可以看到mybatis打印了查詢語句,并在redis服務(wù)器中更新了一條緩存

我們清空控制臺(tái)再次點(diǎn)擊查詢員工按鈕執(zhí)行查詢方法,可以看到?jīng)]有執(zhí)行查詢語句,證明第二次查詢直接從緩存中取值,沒有連接mysql進(jìn)行查詢。

總結(jié)

以上所述是小編給大家介紹的redis與ssm整合方法(mybatis二級緩存),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • MybatisPlus自動(dòng)填充創(chuàng)建(更新)時(shí)間問題

    MybatisPlus自動(dòng)填充創(chuàng)建(更新)時(shí)間問題

    在開發(fā)數(shù)據(jù)庫相關(guān)應(yīng)用時(shí),手動(dòng)設(shè)置創(chuàng)建和更新時(shí)間會(huì)導(dǎo)致代碼冗余,MybatisPlus提供了自動(dòng)填充功能,通過實(shí)現(xiàn)MetaObjectHandler接口并重寫insertFill、updateFill方法,可以自動(dòng)維護(hù)創(chuàng)建時(shí)間、更新時(shí)間等字段,極大簡化了代碼,這不僅提高了開發(fā)效率,也保證了數(shù)據(jù)的可追溯性
    2024-09-09
  • Java注解簡介和使用詳細(xì)講解

    Java注解簡介和使用詳細(xì)講解

    Java 語言中的類、構(gòu)造器、方法、成員變量、參數(shù)等都可以被注解進(jìn)行標(biāo)注,這篇文章主要介紹了Java注解的介紹和使用詳細(xì)講解,需要的朋友可以參考下
    2023-02-02
  • 五個(gè)很實(shí)用的IDEA使用技巧分享

    五個(gè)很實(shí)用的IDEA使用技巧分享

    IntelliJ IDEA 是一款優(yōu)秀的 Java 集成開發(fā)環(huán)境,它提供了許多強(qiáng)大的功能和快捷鍵,可以幫助開發(fā)者提高編碼效率和質(zhì)量,本文就在為你介紹博主常用的五個(gè)IntelliJ IDEA使用技巧,希望能夠給你帶來一些工作效率上的提升
    2023-10-10
  • ElasticSearch如何設(shè)置某個(gè)字段不分詞淺析

    ElasticSearch如何設(shè)置某個(gè)字段不分詞淺析

    最近在學(xué)習(xí)ElasticSearch官方文檔過程中發(fā)現(xiàn)的某個(gè)問題,記錄一下 希望能幫助到后面的朋友,下面這篇文章主要給大家介紹了關(guān)于ElasticSearch如何設(shè)置某個(gè)字段不分詞的相關(guān)資料,需要的朋友可以參考下
    2022-04-04
  • Struts2實(shí)現(xiàn)文件下載功能代碼分享(文件名中文轉(zhuǎn)碼)

    Struts2實(shí)現(xiàn)文件下載功能代碼分享(文件名中文轉(zhuǎn)碼)

    這篇文章主要介紹了Struts2實(shí)現(xiàn)文件下載功能代碼分享(文件名中文轉(zhuǎn)碼)的相關(guān)資料,需要的朋友可以參考下
    2016-06-06
  • Java接收前端請求體的多種方式總結(jié)

    Java接收前端請求體的多種方式總結(jié)

    這篇文章主要給大家介紹了關(guān)于Java接收前端請求體的多種方式,文中通過代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2023-08-08
  • Java 添加、更新和移除PDF超鏈接的實(shí)現(xiàn)方法

    Java 添加、更新和移除PDF超鏈接的實(shí)現(xiàn)方法

    PDF超鏈接用一個(gè)簡單的鏈接包含了大量的信息,滿足了人們在不占用太多空間的情況下渲染外部信息的需求。這篇文章主要介紹了Java 添加、更新和移除PDF超鏈接的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2019-05-05
  • 手寫簡版kedis分布式key及value服務(wù)的實(shí)現(xiàn)及配置

    手寫簡版kedis分布式key及value服務(wù)的實(shí)現(xiàn)及配置

    這篇文章主要為大家介紹了手寫簡版的kedis分布式key及value服務(wù)的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-02-02
  • SpringBoot整合mybatis的方法詳解

    SpringBoot整合mybatis的方法詳解

    這篇文章主要為大家詳細(xì)介紹了SpringBoot整合mybatis的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Java?二維數(shù)組創(chuàng)建及使用方式

    Java?二維數(shù)組創(chuàng)建及使用方式

    這篇文章主要介紹了Java?二維數(shù)組創(chuàng)建及使用方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-08-08

最新評論

汶上县| 布拖县| 湄潭县| 阿拉尔市| 永清县| 吴堡县| 安远县| 田林县| 文化| 米泉市| 安丘市| 台北县| 孙吴县| 新田县| 久治县| 宁安市| 建始县| 稻城县| 鱼台县| 河池市| 日土县| 闻喜县| 洞头县| 松滋市| 凤冈县| 布拖县| 旺苍县| 得荣县| 八宿县| 永年县| 开鲁县| 长子县| 陈巴尔虎旗| 汾西县| 怀安县| 巴里| 昭通市| 福海县| 丹凤县| 临夏市| 革吉县|