이 기간 동안 다양한 문제를 겪었다는 사실을 바탕으로, 나는 그것을 분류하는 것에 대해 생각했습니다. 이 기사는 주로 Spring+Mybatis를 기반으로 한 주석 형태로 Redis의 통합을 소개합니다. 덜 말도 안되고 요점에 도달하십시오.
먼저, Redis를 준비하십시오. 나는 Windows 버전이 될 것입니다. 다운로드 후 Redis-Server를 직접 시작하십시오. 아래 그림을 참조하십시오.
먼저 Jar 패키지를 먼저 추가하십시오
2. 엔티티 클래스를 만듭니다
package com.sl.user.vo; import java.io.serializable; import com.fasterxml.jackson.databind.propernenamingstrategy; import com.fasterxml.jackson.databind.annotation.jsonnaming; import com.fasterxml.jackson.databind.antation.jsonnealize; @jseralize; @jsonnaming (propertynamingstrategy.lowercasewithUnderscorestgrategy.class) 공개 클래스 Uservo는 직렬화 가능한 {private static final long serialversionuid = 1l; private int id; private string username; private int 연령; public uservo () {super (); } public uservo (int id, string username, string password, int age) {super (); this.id = id; this.username = username; this.password = password = this.age = age;} public int getId () {return setid;} public setern (string getUname) username) {this.username = username;} public string getpassword () {return password;} public void setpassword (String password) {this.password = assader;} public int getage () {return age;} public void setage (int age) {this.age = age;}@retainpublic string () {usevo [usevo [usever " username = " + username +", password = " + password +", age = " + age +"];}} 세, DAO 인터페이스
package com.sl.user.dao; import com.sl.user.vo.uservo; public void userdao {public void adduer (uservo user); public void deleteuser (uservo user); public void updateuser (uservo user); public uservo getuserbyid (int id); 4. Usermpper
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype mapper public "-// mybatis.org//dtd Mapper 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd "> mapper Namespace ="com.sl.sl.sl.user.dao.user. > <resultmap id = "userresult"type = "user"> <result column = "id"property = "id"/> <result column = "userame"propertion = "userame"속성 = "userame"/> <result column = "product ="pasure "/> <결과 열 ="age "속성 ="age "속성 ="age "속성 ="age "propert ="age "/> <</resultmap> <insert id ="insert " ParameterType = "user"> t_user (사용자 이름, 비밀번호, Age) 값 (#{username},#{password},#{ageert> <Update id = "deleteUser"ParameterType = "user"> upgate id = apudate ""upgatte "" "upgatte" "upgatte" "upgatte" ""user "> delete *에서 삽입하십시오. t_user set <if test = "username! = null and username! = ''" "> username = #{username}, </if> <test ="password! = null and password! = '' ""> password = {password}, </if> <test = "age! = null and age! = '' '{age = #if> if test! null and id! = '' "> 및 id = # #{id} </if> </update> <select id ="getUser "parameterType ="int "resulttype ="user "> select *에서 t_user에서 id = #{id} </select> <java.lang.lang"> select type = "select> <select type" t_user where id = #{id} </select> </mapper> 5. 서비스 인터페이스
package com.sl.user.service; import com.sl.user.vo.uservo; public interface userervice {public void adduser (uservo user); public void deleteuser (uservo user); public void updateuser (uservo user); public uservo getUserbyid (int id); int);}; 여섯 번째, 서비스 구현
package com.sl.user.service.impl; import org.springframework.bean.beans.beans.annotation.autowired; import org.springframework.cache.annotation.cacheevict; import org.springframework.cache.annotation.cacheevict; import org.springframework.stereporty.service.service.service org.springframework.transaction.annotation.propagation; import org.springframework.transaction.annotation.transactional; import com.sl.user.dao.userdao; import com.sl.user.service.userservice; import com.sl.user.vo.uservo; @service ( "userervice"))@transactional (propagation = procagation.required, relbackfor = exception.class) public class usererviceimpl emerservice {@autowiredprivate userDao userDao;@value@cacheevict (value = ", key =", key = "", " AddUser (uservo user) {userdao.adduser (user);}@}@atredride@cacheevict (value = { "getUser", "getUserById"}, AllEntries = true) public void deleteuser (uservo user) {userDao.deleteUser (user)@cachevict (value = {getuser ", "getUserById"}, allentries = true) public void updateUser (uservo user) {userDao.upDateUser (user);}@reverride@cachable (value = "user", key = "getUserByid") public uservo getUserByid (int id) {return userDao.getUserById (id);}@retomeride@cachable (value = "user", key = " 'getUser'") public uservo getUser (int id) {return userDao.getUser (id);}} 7, Ctrl 층
package com.sl.user.web; import java.util.hashmap; import java.util.map; import org.springframework.bean.beans.antotation.autowired; import org.springframework.stereotyp.controller; import org.springframework.bind.antation. requestmapp org.springframework.web.bind.annotation.responsebody; import com.sl.user.service.userservice; import com.sl.user.vo.uservo;@controller@requestmapping ( "/userctrl") public userctrl {@autowiredprivice userservice; @RequestMappe ( "/adduser") AddUser (uservo user) {userervice.adduser (user);}@requestMapping ( "/deleteUser") public void deleteUser (uservo user) {userservice.deleteuser (user);}@requestMapping ( "/updateUser") public void updateUser (uservo user) {userervice.updateuser (user);}@responsemapping ( "/getUserByid") 공개 맵 <문자열, 개체> getUserByid (uservo user) {map <string, object> map = new Hashmap <string, object> (); map.put ( "msg", userservice.getuserByid (4)); map;}@responsemapping ( "/getUser") public map <string, object> getUser (uservo vo) {map <string, object> map = new Hashmap <String, Object> (); Object user = userervice.getUser (4); map.put ( "msg", user.toString (); return map;}} 8. CRUD 작업에 사용되는 Redis Key 클래스
package com.sl.user.redis; import java.io.bytearrayinputstream; import java.io.BytearRayoutputStream; import java.io.ioexception; import java.io.objectinputstream; import java.io.objectoutputStream; import java.io.objectoutputStream; org.springframework.cache.cache import; org.springframework.cache.support.simplevaluewrapper; import org.springframework.dao.dataaccessexception; org.springframework.data.redis.connection.redisconnection; org.springframework.data.redis.core.rediscallback; org.springframework.data.redis.core.redistemplate; 공개 클래스 Redisutil은 캐시 {private redistemplate <String, Object> Redistemplate; 개인 문자열 이름; public redistemplate <string, object> getRedistemplate () {return redistemplate; } public void setredistemplate (redistemplate <string, object> redistemplate) {this.redistemplate = redistemplate; } public void setName (문자열 이름) {this.name = 이름; } @override public String getName () {return this.name; } @override public object getNativeCache () {return this.RedistEMPlate; } /*** Cache* /@public valuewrapper get (개체 키) {system.out.println ( "get key"); 최종 문자열 keyf = key.toString (); 객체 객체 = null; Object = redistemplate.execute (new readiscallback <botort> () {public object doinredis (readisconcection connection) {byte [] key = keyf.getBytes (); byte [] value = connection.get (key); if (value == null) {return null; value}); return (Object! = null? new SimpleValueWrapper (Object) : NULL); } /*** 새 키를 캐시에 저장*먼저 이름과 객체를 얻은 다음 ByteArray* /@public void put (객체 키, 개체 값) {System.out.println ( "put key")으로 변환합니다. 최종 문자열 keyf = key.toString (); 최종 객체 값 = 값; 최종 긴 생동감 = 86400; redistemplate.execute (new readiscallback <long> () {public long doinredis (readisconnection connection) dataAccessException {byte [] keyb = keyf.getBytes (); balueb = tobytearray (valuef) (keyb, valueb); if (livetime> 0) {expire (keyb); return 1l; } private byte [] tobytearray (Object obj) {byte [] bytes = null; BytearRayoutputStream BOS = New ByTearRayoutputStream (); try {objectOutputStream oos = new ObjectOutputStream (BOS); oos.writeobject (obj); oos.flush (); 바이트 = bos.tobytearray (); oos.close (); bos.close (); } catch (ioexception ex) {ex.printstacktrace (); } 반환 바이트; } private object toobject (byte [] bytes) {object obj = null; try {bytearrayinputstream bis = new bytearrayinputstream (bytes); ObjectInputStream OIS = New ObjectInputStream (BIS); obj = ois.readobject (); ois.close (); bis.close (); } catch (ioexception ex) {ex.printstacktrace (); } catch (classNotFoundException ex) {ex.printstacktrace (); } return obj; } /*** key* /@public void evict (개체 키) {system.out.println ( "del key"); 최종 문자열 keyf = key.toString (); redistemplate.execute (새로운 readiscallback <long> () {public long doinredis (Redisconnection Connection) DataAccessException {return connection.del (keyf.getBytes ());}); } /*** CLEAR 키* /@public void clear () {system.out.println ( "Clear Key"); redistemplate.execute (new readiscallback <string> () {public string doinredis (readisconnection connection) dataAccessException {connection.flushdb (); return "ok";}}); } @override public <t> t get (개체 키, 클래스 <t> type) {return null; } @override public valuewrapper putifabsent (객체 키, 객체 값) {return null; }} 스프링은 mybatis 및 redis 구성 파일을 통합합니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : p = "http://www.springframework.org/schema/p"xmlns : context = "http://www.springframework.org/schema/context" xmlns : tx = "http://www.springframework.org/schema/tx"xmlns : mvc = "http://www.springframework.org/schema/mvc"xmlns : aop = "http : //www.spramew ork.org/schema/aop"xmlns:cache="http://www.springframework.org/schema/cache"xsi:schemalocation="http://www.spramframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/sprring-sp-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.spramework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache.xsd" • scan dao-, service BASE-PACKAGE = "com.sl.user.service" /> <context : component-scan base-package = "com.sl.user.service.*" /> <context : component-scan base-package = "com.sl.user.redis" /> <!-enable annotation-> antable-cach />. 주석-> <캐시 : 주석 구동/> <!-myBatis start-> <!-DataSource DriverManagerDatasource 구성-> <bean id = "dataSource"> <property name = "driverclassName"value = "com.mysql.jdbc.driver"> <속성 이름 = "url" value = "value ="jdbc : mysql : //127.0.0.1 : 3306/test "> </property> <property name ="username "value ="root "> </property name ="property name = "root"> </property> </bean> <!-mybatis configuration sqlsessionfactorybean-> <aid = "id =" "id ="id id = " ref = "dataSource"> </property> <속성 이름 = "configlocation"value = "classPath : config/mybatis.xml"> </property> <속성 이름 = "mapperlocations"value = "classpath : mapper/usermapper.xml"> </property> </bean> <!- MyBatis Automatic Scan to SQL MAP 파일 : MapperCantofit/Mybatis Automatic Scan. SQLSESSIONFACTORYBASEPACKAGE : SQL 맵 파일/인터페이스가 위치한 패키지를 지정합니다 (자동 스캔)-> <ean> <속성 이름 = "sqlsessionFactory"ref = "sessionFactory"> </property> <속성 이름 = "BasePackage"value = "com.sl.user.dao"> </bean> <transatomation management dataSoupeCetransomer id = "txmanager"> <property name = "dataSource"ref = "dataSource"> </property> </bean> <!-선언 트랜잭션-관리자 사용 : 위에 정의 된 트랜잭션 관리자를 참조하십시오-> <tx : 주석 중심 트랜잭션-매너 = "txmanager"> </tx : annotation-driven> <!-mybatis angis-> <! -> <!-Redis Connection Pool JedisPoolConfig-> <bean id = "poolconfig"> <속성 이름 = "maxidle"value = "300" /> <property name = "maxtotal"value = "600" /> < /bean> <!-configure coonnection jedisconnectionfactory-> <bean name "> <property name"> value = "127.0.0.1"> </property> <속성 이름 = "port"value = "6379"> </property> <property name = "poolconfig"ref = "poolconfig"> </property> </bean> <!-Redistemplate StringRedistemplate-> <bean id = "Redistemplate"> <bone-reg = "reff. id = "cachemanager"> <property name = "caches"> <bean> <bean> <property name = "redistemplate"ref = "redistemplate"/> <property name = "name"value = "user"/<!-사용자 이름은 클래스 또는 메소드 주니어에서 사용해야합니다-> </bean> </set> </bean> </bean>
10, SpringMVC 구성 파일
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : p = "http://www.springframework.org/schema/p"xmlns : context = "http://www.springframework.org/schema/tx" xmlns : mvc = "http://www.springframework.org/schema/mvc"xmlns : aop = "http://www.springframework.org/schema/schema/aop"xsi : skemalocation = "http://www.spramframwork.org/schema http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.spramework.org/schema/tx/sprring-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"><<<<<<<<<<<<<< <컨텍스트 : context : annotation-config/> <!-- 컨텍스트가 위치한 클래스가 위치한 JAR 패키지를 설정하십시오. BASE-PACKAGE = "com.sl.user.*"> "> </context : component-scan> <!-모델보기 이름의 해상도, 즉 모델보기 이름에 접두사 추가-> <bean id ="veen id = "veen id ="veen id = "veen id ="veen id = "voaty"value = "org.springframework.webiew.view.jstlview.jstlview"/>>>>>>>>>>>>>> <propertlview.jstlview. value = "/views/"/> <속성 이름 = "접미사"value = " name = "supportedMediAtypes"> <list> <value> application/json; charset = utf-8 </value> <value> text/json; charset = utf-8 </value> </list> </bean> </list> </property> </bean> </beans>
11, myBatis 구성 파일
<? xml version = "1.0"encoding = "utf-8"?> <! doctype configuration public "-// mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> inity classe, abbrevated- 별칭-> <failiases> <faultealias alias = "user"type = "com.sl.user.vo.uservo"/> </failiases> </configuration>
12, log4J
# 루트 카테고리 설정 정보 및 Console.LOG4J.ROOTCATEGORY = DEBUG, CONSOLE# log4J.RootCategory = Info, Console, Logfile# 콘솔은 A를 사용하여 ConsolePender로 설정됩니다. PatternLayout.log4j.appender.console = org.apache.log4j.consoleappenderlog4j.appender.console.console.console.threshold = debuglog4j.a ppender.console.layout = org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern =%d {yyyy-mm-dd hh/: mm/: ss} %p- %m %m %nlog4j.logger.java.sql.connection = debuglog4j.logger.java.sql.statement = debuglog4j.logger.java.sql.sql.preparedstatement = debuglog4j.logger.java.sql.resgests = 13, web.xml
<? xml version = "1.0"encoding = "utf-8"?> <web-app version = "3.0"xmlns = "http://java.sun.com/xml/xml/ns/javaee"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance. xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>testredis</display-name><context-param> <param-name-name>contextconfiglocation</param-n AME> <Param-value> classPath : config/applicationcontext.xml </param- value> </context-param> <context-param> <param-name> log4jconfiglocation </param-name> <p ARAM-Value> ClassPath : config/log4j.properties </param-value> </context-param> <context-param> <param-name> log4jrefreshinterval </param-name> <param-value > 60000 </param-value> </context-param> <Leater> <Leater-class> org.springframework.web.context.contextloaderListener </Learter-Class> </laiseer> <!- log-> <layer> <layer-class> org.springframework.web.util.log4jconfiglistener </lareer-class> </lareer-class> </lareer> <servlet> <servlet-name> spring </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherserv </servletserver> ContextConfigLocation </param-name> <param-value> classpath : config/springmvc.xml </param-value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name> spring </servlet-name> </url-pattern>*. 중국어 코드의 문제를 해결하십시오 -> <filter> <filter-name> 캐릭터 encoding </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filt ER-Class> <Init-Param> <Param-Name> 인코딩 </param-name> <param- value> utf-8 </param-value> </init-param> <init-param> <param-name> forceen 코딩 </param-name> <param- value> true </param-value> </init-param> </filter> <filter-mapping> <filter-name> 캐릭터 encoding </filter-name> < url-pattern>*
14 세의 테스트는 예제 (getUser () 메소드)로 쿼리되었으며 JSP 테스트 페이지는 추악하므로 게시하지 않고 직접 작성하십시오. . .
쿼리 전 :
첫 번째 쿼리 실행 :
두 번째 쿼리 작업 수행 :
위 그림에서 볼 수 있듯이 SQL은 다시 실행되지 않으며 Redis에서 데이터를 직접 얻습니다.
위의 것은 편집기의 주석을 기반으로 Redis를 통합하는 방법입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!