ssm + redis
生活随笔
收集整理的這篇文章主要介紹了
ssm + redis
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
個人經驗,需要的話可以一看
windows 64位redis下載地址
點擊打開鏈接
首先:安裝redis服務器,分別運行redis-server.exe,redis-cli.exe,并在redis-cli.exe中設置密碼(如下圖)
接下來進入項目,注解都在項目中,可以自己看
??
首先我們要新建一個緩存類RedeisCache
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;/*** * @描述: 使用第三方內存數據庫Redis作為二級緩存* @版權: Copyright (c) 2017* @作者: juin* @版本: 1.0 * @創建日期: 2017年10月30日 * @創建時間: 下午8:02:57*/ public class RedisCache implements Cache {private static Logger logger = LoggerFactory.getLogger(RedisCache.class); /** The ReadWriteLock. */ private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();private String id;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 String getId() {return this.id;}public void putObject(Object key, Object value) {logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);RedisUtil.getJedis().set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));}public Object getObject(Object key) {Object value = SerializeUtil.unserialize(RedisUtil.getJedis().get(SerializeUtil.serialize(key.toString())));logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:"+key+"="+value);return value;}public Object removeObject(Object key) {return RedisUtil.getJedis().expire(SerializeUtil.serialize(key.toString()),0);}public void clear() {RedisUtil.getJedis().flushDB();}public int getSize() {return Integer.valueOf(RedisUtil.getJedis().dbSize().toString());}public ReadWriteLock getReadWriteLock() {return readWriteLock;}}然后需要一個工具類
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig;public final class RedisUtil {// Redis服務器IPprivate static String ADDR = "127.0.0.1";// 測試服務器//private static String ADDR = "192.168.12.134";// Redis的端口號private static int PORT = 6379;// 訪問密碼private static String AUTH = "123456";//訪問密碼//可用連接實例的最大數目,默認值為8;//如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis實例,則此時pool的狀態為exhausted(耗盡)。private static int MAX_ACTIVE = 1024;//控制一個pool最多有多少個狀態為idle(空閑的)的jedis實例,默認值也是8。private static int MAX_IDLE = 200;//等待可用連接的最大時間,單位毫秒,默認值為-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException;private static int MAX_WAIT = 10000;private static int TIMEOUT = 10000;//在borrow一個jedis實例時,是否提前進行validate操作;如果為true,則得到的jedis實例均是可用的;private static boolean TEST_ON_BORROW = true;private static JedisPool jedisPool = null;/*** 初始化Redis連接池*/static {try {JedisPoolConfig config = new JedisPoolConfig();// config.setMaxActive(MAX_ACTIVE);config.setMaxTotal(MAX_ACTIVE);config.setMaxIdle(MAX_IDLE);config.setMaxWaitMillis(MAX_WAIT);// config.setMaxWait(MAX_WAIT);config.setTestOnBorrow(TEST_ON_BORROW);jedisPool = new JedisPool(config, ADDR, PORT, 100000, AUTH);System.out.println("redis密碼");} catch (Exception e) {e.printStackTrace();}}/*** 獲取Jedis實例* @return*/public synchronized static Jedis getJedis() {try {if (jedisPool != null) {Jedis resource = jedisPool.getResource();return resource;} else {return null;}} catch (Exception e) {e.printStackTrace();return null;}}/*** 釋放jedis資源* @param jedis*/public static void returnResource(final Jedis jedis) {if (jedis != null) {jedisPool.returnResource(jedis);}}/*** * 判斷用戶是否過期* * @param jedis*/public static boolean VerifyUser(String id) {String key = RedisUtil.getJedis().get(id);if (key == null) {return false;}return true;} }最后是一個關于序列化的類
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializeUtil { /** * 序列化 * * @param object * @return */ 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) { } return null; } /** * 反序列化 * * @param bytes * @return */ public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; } }配置文件自然也是少不了的
首先是spring-redis配置文件
spring-redis:
propertis:
redis.maxIdle=300 redis.minIdle=100 redis.maxWaitMillis=3000 redis.testOnBorrow=true redis.maxTotal=500 redis.host=127.0.0.1 redis.port=6379 redis.password=123456
務必要在web.xml里面聲明位置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mybatis.xml,classpath:spring-redis.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--spring配置文件路徑 --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><session-config><session-timeout>30</session-timeout></session-config><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>另外也是要在spring-mybatis文件里面開啟一下緩存
<?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:p="http://www.springframework.org/schema/p"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-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><context:component-scan base-package="com.qdu"/> <tx:annotation-driven transaction-manager="txManager" /><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/classmanagesys" /><property name="username" value="root" /><property name="password" value="118554" /><!-- 19951211 --><!-- 118554 --></bean><!-- 開啟事務及redis緩存 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath:com/qdu/mapping/*.xml" /> <property name="configurationProperties"> <props><prop key="cacheEnabled">true</prop> <prop key="lazyLoadingEnabled">false</prop> <prop key="aggressiveLazyLoading">true</prop></props></property></bean><bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><tx:annotation-driven transaction-manager="txManager" /></beans>最后一步,在映射文件下面加上一句話
別忘了改一下配置
打開redis.windows.conf,找到 #requirepass?foobared ,去掉 # ,改為requirepass 123456
測試,成功
import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig;public class RedisTest {JedisPool pool;Jedis jedis;@Beforepublic void start() {// 初始化Redis連接池pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1");// 從Redis連接池中獲取一個連接jedis = pool.getResource();// Redis的密碼,對應redis.windows.conf中的masterauthjedis.auth("123456");}/*** 添加測試*/@Testpublic void putTest() {jedis.set("user", "adwina");System.out.println(jedis.get("user"));}/*** 覆蓋測試*/@Testpublic void overWriteTest() {jedis.set("user", "Juin");System.out.println(jedis.get("user"));}/*** 追加測試*/@Testpublic void appendTest() {jedis.append("user", "侯亞軍");System.out.println(jedis.get("user"));}/*** 刪除測試*/@Testpublic void deleteTest() {jedis.del("user");System.out.println(jedis.get("user"));// 輸出結果:null}}總結
以上是生活随笔為你收集整理的ssm + redis的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大学计算机实验vfp,Visual Fo
- 下一篇: 物理模型图设计