بناءً على حقيقة أنني واجهت مشاكل مختلفة خلال هذه الفترة الزمنية ، فكرت في حلها. تقدم هذه المقالة بشكل أساسي تكامل Redis في شكل تعليقات توضيحية على أساس Spring+MyBatis. أقل هراء ، وصلت إلى هذه النقطة.
أولا ، إعداد redis. سأستخدم إصدار Windows. بعد التنزيل ، ما عليك سوى بدء Redis Server مباشرة. انظر الصورة أدناه:
أولاً ، أضف حزمة الجرة أولاً
2. إنشاء فئة كيان
package com.sl.user.vo ؛ import java.io.serializable ؛ استيراد com.fasterxml.jackson.databind.propertynamingtrategy ؛ استيراد com.fasterxml.jackson.databind.annotation.jsonnaming ؛ jSonnaming (propertynamingstrategy.lowercasewithundersCoreStrategy.Class) الطبقة العامة uservo تنفذ {private static static final long serialversionuid = 1l ؛ int id ؛ private string username ؛ private string password ؛ private int age ؛ public uservo () {super () ؛ } public uservo (int id ، اسم مستخدم السلسلة ، كلمة مرور السلسلة ، int ation) {super () ؛ this.id = id ؛ this.username = username ؛ this.password = this.age = age ؛} public int getId () {return id} public void setId (int id) {this.id = id ؛ id ؛ اسم المستخدم) {this.username = username ؛} السلسلة العامة getPassword () {return password ؛} public void setPassword (سلسلة كلمة مرور) {this.password = password ؛} public int getage () {return Age ؛ + اسم المستخدم + "، password =" + password + "، Age =" + Age + "]" ؛}} ثلاثة ، واجهة داو
package com.sl.user.dao ؛ استيراد com.sl.user.vo.uservo ؛ واجهة عامة userdao {public void adduser (uservo user) ؛ public void deleteuser (uservo user) ؛ 4. USERMAPPER
<؟ > <resultmap id = "userresult" type = "user"> <result column = "id" property = "id"/> <result column = "userame" property = "userame"/> <result column = "password" property = "password"/> <result column = "Age" enser "enser"/> <result column = "age"/ parametertype = "user"> insert في T_USER (اسم المستخدم ، كلمة المرور ، العمر) قيم (#{username} ،#{password} ،#{Age}) </insert> <update id = "devateuser T_USER SET <if test = "username! = null و username! = ''"> اسم المستخدم = #{username} ، </if> <if test = "password! = null و password! = '' null and id! = '' "> and id = #{id} </fort> </uptuday> <select id =" getUser "parametertype =" int "resulttype =" user "> select * from t_user where id = #{id} </select> <select id = T_USER حيث id = #{id} </select> </mapper> 5. واجهة الخدمة
package com.sl.user.service ؛ import com.sl.user.vo.uservo ؛ public interface uservice {public void adduser (uservo user) ؛ public void deleteuser (uservo user) ؛ public void update (uservo user) ؛ public uservo getuserbyid (int id) ؛ السادس ، تنفيذ الخدمة
package com.sl.user.service.impl ؛ استيراد org.springframework.beans.factory.annotation.autowired ؛ استيراد org.springframework.cache.antation.cacheevict org.springframework.transaction.annotation.propagation ؛ استيراد org.springframework.transaction.antantation.transactional ؛ استيراد com.sl.user.dao.userdao ؛ استيراد com.sl.user.service.userservice ؛ استيراد الاستيراد ؛ com.sl.user.vo.uservo ؛ service ("userService")@Transactional (spection. addUser (uservo user) {userDao.adduser (user) ؛}@override@cacheevict (value = {"getUser" ، "getUserById"} ، allentries = true) public void deleteuser (uservo user) "getUserById"} ، allentries = true) public void updateUser (uservo user) {userDao.upDateuser (user) ؛}@override@cachable (value = "user" ، key = "getUserById) userDao.getuserById (id) ؛}@override@cachable (value = "user" ، key = "'getuser'") public uservo getuser (int id) {return userDao.getuser (id) ؛}} سبعة ، طبقة Ctrl
حزمة com.sl.user.web ؛ استيراد java.util.hashmap ؛ استيراد java.util.map ؛ استيراد org.springframework.beans.factory.annotation.autowired org.springframework.web.bind.annotation.responsebody ؛ import com.sl.user.service.userservice ؛ import com.sl.user.vo.uservo ؛@controller@requestmappic ("/userctrl") public class agerctrl addUser (uservo user) {uservervice.adduser (user) ؛}@requestMapping ("/deleteuser") public void deleteuser (uservo user) {uservice.deleteuser (user) ؛}@requestmapp user) {sterverservice.updateuser (user) ؛}@reponseBody@requestMapping ("/getUserById") الخريطة العامة <string ، object> getUserById (uservo user) {map <string ، object> map = new hashmap <string ، object> () ؛ map.pt ("msg" ، userService.getUserbyid (4)) ؛ MAP ؛}@reponseBody@requestMapping ("/getUser") الخريطة العامة <string ، object> getUser (uservo vo) {map <string ، object> map = new hashmap <string ، object> () 8. فئة مفتاح Redis ، تستخدم لعمليات CRUD
حزمة com.sl.user.redis ؛ استيراد java.io.bytearrayinputstream ؛ استيراد java.io.bytearrayoutputstream ؛ استيراد java.io.ioException ؛ استيراد java.io.objectinputStream ؛ استيراد java.io.objectOutputStream ؛ استيراد java.io.objectOutputStream ؛ استيراد org.springframework.cache.cache ؛ استيراد org.springframework.cache.support.simplevaluewrapper ؛ استيراد 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 ؛ اسم السلسلة الخاصة ؛ redistemplate public <string ، object> getRedIstemplate () {return redistemplate ؛ } public void setRediStemplate (redistemplate <string ، object> redistemplate) {this.redistemplate = redistemplate ؛ } public void setName (اسم السلسلة) {this.name = name ؛ } Override public string getName () {return this.name ؛ } Override public object getNativeCache () {return this.redistemplate ؛ } /*** احصل على مفتاح من ذاكرة التخزين المؤقت* /@@override publuewrapper get (مفتاح الكائن) {system.out.println ("get key") ؛ السلسلة النهائية keyf = key.toString () ؛ كائن كائن = فارغ ؛ object = redistemplate.execute (جديد إعادة regallback <hompour> () {كائن عام doinredis (اتصال redisconnection) يلقي DataAccessException {byte [] key = keyf.getBytes () ؛ byte [] value = connection.get (key) ؛ if (value == null) {return null ؛ إرجاع (كائن! = null؟ جديد SimpleValuewRapper (كائن): NULL) ؛ } /*** احفظ مفتاحًا جديدًا إلى ذاكرة التخزين المؤقت*أولاً احصل على الاسم والكائن ثم تحويله إلى bytearray* /@override public void pub (مفتاح الكائن ، قيمة الكائن) {system.out.println ("but key") ؛ السلسلة النهائية keyf = key.toString () ؛ قيمة الكائن النهائي = القيمة ؛ LIVETIME النهائي = 86400 ؛ redistemplate.execute (إعادة صياغة جديدة <Ngt> () {public doinredis (connection redisconnection) يلقي dataAccessException {byte [] keyb = keyf.getbytes () 1L ؛ } private byte [] tobytearray (object obj) {byte [] bytes = null ؛ bytearrayoutputstream bos = جديد bytearrayoutputStream () ؛ حاول {ObjectOutputStream OOS = New ObjectOutputStream (BOS) ؛ OOS.WriteObject (OBJ) ؛ ooos.flush () ؛ bytes = bos.tobytearray () ؛ oos.close () ؛ bos.close () ؛ } catch (ioException ex) {ex.printStackTrace () ؛ } إرجاع بايت ؛ } كائن خاص tobject (byte [] bytes) {object obj = null ؛ حاول {bytearrayinputStream Bis = جديد bytearrayinputStream (bytes) ؛ ObjectInputStream OIS = New ObjectInputStream (BIS) ؛ obj = ois.ReadObject () ؛ ois.close () ؛ bis.close () ؛ } catch (ioException ex) {ex.printStackTrace () ؛ } catch (classNotFoundException ex) {ex.printStackTrace () ؛ } إرجاع OBJ ؛ } /*** حذف المفتاح* /@@outride public void evict (مفتاح الكائن) {system.out.println ("del key") ؛ السلسلة النهائية keyf = key.toString () ؛ redistemplate.execute (جديد rediscallback <tong> () {public doinredis (Redisconnection Connection) يلقي DataAccessException {return connection.del (keyf.getbytes ()) ؛}}) ؛ } /*** clear key* /@override public void clear () {system.out.println ("clear key") ؛ redistemplate.execute (جديد rediscallback <string> () {public string doinredis (redisconnection connection) يلقي dataAccessException {connection.flushdb () ؛ إرجاع "OK" ؛}}) ؛ } Override public <t> t get (مفتاح الكائن ، الفئة <T> type) {return null ؛ } Override publuewrapper putifabsent (مفتاح الكائن ، قيمة الكائن) {return null ؛ }} 9. يدمج الربيع ملفات تكوين MyBatis و Redis
<؟ xmlns: p = "http://www.springframework.org/schema/p" xmlns: tx = "http://www.springframework.org/schema/tx" ork.org/schema/aop"xmlns:cache="http://www.springframework.org/schema/cache"xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springfframework.org/schemaxt http://www.springframework.org/schema/context/spring-context-4.0.xsdhtp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhtp://www.springframework.org/schema/cache http://www.springframework.org/schema/cached -> <السياق: مكون مسكك الأساس package = "com.sl.user.service" /> <context: component-scan base-package = "com.sl.user.service. شرح ذاكرة التخزين المؤقت-> <ذاكرة التخزين المؤقت: يحركه التعليق التوضيحي/> <!-MyBatis start-> <!-تكوين DataSource DriverManagerDataSource-> <bean id = "datasource"> <property name = "driverClassName" value = "com.mysql.jdbc.dbc.driver value = "jdbc: mysql: //127.0.0.1: 3306/test"> </propect ref = "datasource"> </spleneration> <property name = "configlocation" value = "classpath: config/mybatis.xml"> </sprement> <property name = "mapperlocations" value = "classpath: mapper/usermapper.xml"> </property> <! SQLSessionFactoryBasePackage: حدد الحزمة التي يوجد بها ملف/واجهة خريطة SQL (المسح التلقائي)-> <Bean> <property name = "sqlsessionfactory" ref = "sessionfactory"> </property> <property name = "basepackage" value = "com.sl.user.dao" datasourCeTransActionManager-> <bean id = "txmanager"> <property name = "dataSource" ref = "datasource"> </property> </bean> <!-باستخدام المعاملة التعريفية: مرجع مدير المعاملات أعلاه-> <tx: التعليقات التعليمية-manager = "txmanager" MyBatis End-> <!-تكوين جزء redis ابدأ-> <!-تكوين Redis Connection Pool JedispoolConfig-> <bean id = "poolconfig"> <property name = "maxidle" value = "300" /> <property name = "maxtotal" value = "600" id = "connfactory"> <property name = "hostname" value = "127.0.0.1"> </sprention> <property name = "port" value = "6379"> </propert name = "connectionfactory" ref = "connfactory"/> </bean> <bean id = "cachemanager"> <property name = "caches"> <set> <biet> <property name = "redistemplate" ref = "redistemplate"/> <property name = "name" value =! </bean> </bans>
10 ، ملف تكوين springMVC
<؟ xmlns: p = "http://www.springframework.org/schema/p" Xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: aop = "http: //www.springfra mework.org/schema/aop"xsi:schemalocation="http://www.springframework.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 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <mvc: annotation-driven/><<!-تمكين التعليقات الرباعية: <context: anotation-config/> <! base-package = "com.sl.user.*"> </context: component-scan> <!-دقة اسم عرض النموذج ، أي إضافة البادئات إلى اسم عرض النموذج-> <bean id = "viewResolver"> <property name = "viewClass" value = "org.springframewwork.web.servlet.view.view.iview value = "/views/"/> <property name = "falue" value = ". name = "supportedMediAtypes"> <list> <value> application/json ؛ charset = utf-8 </value> <sualit> text/json ؛ charset = utf-8 </value> </list> </swerperation> </bean> </list> </sprement> </bult> </bans> </levens>
11 ، ملف تكوين MyBatis
<؟ الاسم المستعار-> <typealiases> <typealias alias = "user" type = "com.sl.user.vo.uservo"/> </termealiases> </ispification>
12 ، log4j
# قم بتعيين فئة الجذر الأولوية على Info و Addender الوحيدة إلى Console.log4j.rootcategory = debug ، وحدة التحكم# log4j.rootcategory = info ، وحدة التحكم ، وحدة تسجيل الدخول# تم تعيينها على موازنة باستخدام أ patternlayout.log4j.appender.console = org.apache.log4j.consoleAppenderlog4j.appender.console.throshold = debuglog4j.appender.console.layout = org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern HH/: mm/: ss} ٪ p - ٪ m ٪ nlog4j.logger.java.sql.connection = debuglog4j.logger.java.sql.statem
Thirteen ، Web.xml
<؟ 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> contextConfiglocation</param-n AME> <Param-value> classpath: config/applicationContext.xml </param-value> </suctext-param> <context-param> <Param-name> log4jConfigLocation </param-name> <p Aram-value> classpath: config/log4j.properties </param-value> </suctext-param> <context-param> <param-name> log4jrefreshinterval </param-name> <param-value > 60000 </param-value> </suctext-param> <stanker> <cleder-class> org.springframework.web.context.contextloaderListener </stanker-class> </nistener> <!- LOG-> <ENDANRER> <CANDRER-CLASS> org.springframework.web.util.log4jConfigListener </leader-class> </stanker> <Servlet> <Servlet-Name> spring </questlet-name> <Sradlet-class> org.springframewwork.web.servlet.dispattervaustv contextConfigLocation </param-name> <Param-value> classpath: config/springmvc.xml </parm-value> </ith-param> <load-on-startup> 1 </odlo-on-startup> </ervlet> </servlet mapping> حل مشكلة الكود الصيني المشوه -> <iliter> <filter-name> directioneding </filter-name> <ilter-class> org.springframework.web.filter.characterencodingfilter </filet er-class> <Ing-param> <Param-Name> الترميز </param-name> <param-value> utf-8 </parm-value> </IPT-param> <Ing-param> <Parm-Name> forceen الترميز </param-name> <param-value> true </param-value> </IPT-PARAM> </filter> <filter-mapping> <filter-name> directionDing </filter-name> < url-pattern>*. do </url-pattern> </filter-mapping> <-list-file-list> <lispile-file> index.jsp </iship-file> </iship-file-list> </web-app>
تم الاستعلام عن أربعة عشر ، اختبارًا ، كأسلوب (getUser ()) ، صفحة اختبار JSP قبيحة ، لذلك لن نشرها ، فقط أكتب بنفسي. . .
قبل الاستعلام:
تنفيذ الاستعلام الأول:
إجراء عملية الاستعلام الثانية:
كما يتضح في الشكل أعلاه ، لا يتم تنفيذ أي SQL مرة أخرى ، ويتم الحصول على البيانات مباشرة من redis.
ما سبق هو طريقة دمج redis بناءً على التعليقات التوضيحية من قبل المحرر. آمل أن يكون ذلك مفيدًا للجميع. إذا كان لديك أي أسئلة ، فيرجى ترك رسالة لي وسوف يرد المحرر على الجميع في الوقت المناسب. شكرا جزيلا لدعمكم لموقع wulin.com!