少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

          #

          蝦米(354668137)  11:17:35
          memcached的數(shù)據(jù)怎么與數(shù)據(jù)庫的數(shù)據(jù)保持同步啊??
          南京-HF(226358522)  11:18:04
          手動同步
          南京-HF(226358522)  11:18:06
          代碼實現(xiàn)
          滄海長風(fēng)(136419390)  11:18:12
          兩邊同時寫
          滄海長風(fēng)(136419390)  11:18:31
          或者定期寫
          滄海長風(fēng)(136419390)  11:18:35
          或者特定條件寫
          蝦米(354668137)  11:19:23
          額,memcached沒有提供相關(guān)的支持嗎
          南京-HF(226358522)  11:20:30
          有個對mysql的同步的庫
          南京-HF(226358522)  11:20:49
          是由mysql同步數(shù)據(jù)到memcached的
          ζ 過了時的流行 ?(779014475)  11:21:13
          蝦米(354668137)  11:17:35
          memcached的數(shù)據(jù)怎么與數(shù)據(jù)庫的數(shù)據(jù)保持同步?。??
          ζ 過了時的流行 ?(779014475)  11:21:16
          同求。
          南京-HF(226358522)  11:21:22
          他的機制也就是,寫都是往mysql寫,查詢從memcached里面查詢
          ζ 過了時的流行 ?(779014475)  11:22:29
          這樣寫mysql的時候同樣得更新mc吧。

           

          南京-HF(226358522)  11:22:44

          ζ 過了時的流行 ?(779014475)  11:22:50
          加mc 本來就是為了減少mysql操作的。。
          ζ 過了時的流行 ?(779014475)  11:22:54
          這樣子都沒啥意義了。。
          南京-HF(226358522)  11:23:07
          應(yīng)該是mysql里面有觸發(fā)器,當數(shù)據(jù)有改變,就會同步到memcached
          南京-HF(226358522)  11:23:30
          就看你以哪個數(shù)據(jù)為主了
          南京-HF(226358522)  11:24:04
          這樣memcached的目的就是加快你的查詢速度
          滄海長風(fēng)(136419390)  11:24:18
          這方案根據(jù)自己需求設(shè)定
          滄海長風(fēng)(136419390)  11:24:23
          組合很多吧
          ζ 過了時的流行 ?(779014475)  11:25:03
          最近也碰到。。mysql與mc同步的。。不知道有啥好方案
          南京-HF(226358522)  11:25:08
          畢竟,查詢用的是最多的。修改或者插入的話,數(shù)據(jù)庫的數(shù)據(jù)必須得邊,所以才有這么個方案。當然這個也不一定適合你們的場景,你自己取舍
          南京-HF(226358522)  11:26:21
          如果你的數(shù)據(jù),增刪改查都很頻繁那這種就不適合了
          ζ 過了時的流行 ?(779014475)  11:26:54
          恩。。這樣的話讀寫都直接對mc操作。。然后定時同步。。
          ζ 過了時的流行 ?(779014475)  11:27:09
          但是蛋疼的就是同步方案。。


          ζ 過了時的流行 ?(779014475)  11:27:25
          不好做增量同步。。
          滄海長風(fēng)(136419390)  11:27:31
          有時做些冗余是不錯的
          ζ 過了時的流行 ?(779014475)  11:27:36
          服務(wù)端用c寫的。


          package lc.abin.lee.reflect;

          import java.lang.reflect.Constructor;
          import java.lang.reflect.Method;

          public class MyMethod {
           private static String name;
           public MyMethod() {
           }
           public MyMethod(String myname) {
            this.name=myname;
           }
           public static String getName(){
            return name;
           }
           public static String getMessage(){
            return "北京歡迎您";
           }
           public static String result(String message){
            return message.replace("my", "abin");
           }
           public static int status(int enter,int end){
            return end+enter;
           }
           public static void main(String[] args) throws Exception {
            MyMethod my=new MyMethod();
            Class<?> cls=my.getClass();
            Method mes=cls.getDeclaredMethod("getMessage");
            String message=(String)mes.invoke(my);
            System.out.println("message="+message);
            Method mld=cls.getDeclaredMethod("result", String.class);
            String result=(String)mld.invoke(my,"myarea");
            System.out.println("result="+result);
            Method plus=cls.getDeclaredMethod("status",int.class,int.class);
            int status=(Integer)plus.invoke(my,5,195);
            System.out.println("status="+status);
            
            Class<?>[] cl={String.class};
            Constructor<?> cul=cls.getConstructor(cl);
            Object obj=cul.newInstance("abin1");
            System.out.println("obj="+obj.getClass());
            Method nmd=cls.getDeclaredMethod("getName");
            String gong=(String)nmd.invoke(cl);
            System.out.println("gong="+gong);
            
           }
          }

          posted @ 2012-10-22 23:52 abin 閱讀(1757) | 評論 (0)編輯 收藏

               摘要: 1、原子性(Atomicity) 事務(wù)的原子性是指事務(wù)中包含的所有操作要么都做,要么都不做,保證數(shù)據(jù)庫是一致的。 例如:A帳戶向B帳戶劃賬1000,則先將A減少1000,再將B增加1000,這兩個動作要么都提交,要么都回退,不可能發(fā)生一個有效、一個無效的情況。 2、一致性(Consistency) 一致性是指數(shù)據(jù)庫在事務(wù)操作前和事務(wù)處理后,其中的數(shù)據(jù)必須都滿足業(yè)務(wù)規(guī)則約束。 ...  閱讀全文
          posted @ 2012-10-21 16:37 abin 閱讀(3234) | 評論 (0)編輯 收藏

          //web.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <web-app xmlns:xsi=" xmlns="http://java.sun.com/xml/ns/javaee  id="WebApp_ID" version="3.0">
           <display-name>universal</display-name>
           <!-- spring -->
           <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:com/abin/lee/ssh/spring-service.xml</param-value>
           </context-param>
           <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
           </listener>


           <!-- spring MVC -->
           <servlet>
            <servlet-name>spring-mvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>classpath*:com/abin/lee/ssh/spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>2</load-on-startup>
           </servlet>
           <servlet-mapping>
            <servlet-name>spring-mvc</servlet-name>
            <url-pattern>/mvc/*</url-pattern>
           </servlet-mapping>
           <!-- spring encoding -->
           <filter>
            <filter-name>utf8-encoding</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>utf8-encoding</filter-name>
            <url-pattern>/*</url-pattern>
           </filter-mapping>

           


           <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
           </welcome-file-list>
          </web-app>





          //spring-mvc.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="
           xmlns:xsi=" xmlns:context=" xmlns:mvc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
              http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
              http://www.springframework.org/schema/util  <!-- 指定系統(tǒng)尋找controller路徑 -->
           <mvc:annotation-driven>
            <!-- json 數(shù)據(jù)格式轉(zhuǎn)換-->
            <mvc:message-converters>
             <bean class="com.abin.lee.ssh.function.FastJsonAbstractHttpMessageConverter">
              <property name="supportedMediaTypes" value="application/json" />
              <property name="serializerFeature">
               <list>
                <value>WriteMapNullValue</value>
                <value>QuoteFieldNames</value>
               </list>
              </property>
             </bean>
            </mvc:message-converters>

           </mvc:annotation-driven>
           <!-- 搜索的包路徑 -->
           <context:component-scan base-package="com.abin.lee.ssh"
            use-default-filters="false">
            <context:include-filter type="annotation"
             expression="org.springframework.stereotype.Controller" />
           </context:component-scan>

          </beans>





          //spring-service.xml
          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="
           xmlns:xsi=" xmlns:context=" xmlns:jdbc="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
              http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd 
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
              http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 
              http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd 
              http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd 
             http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd 
              http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
             http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd 
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd 
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
              http://www.springframework.org/schema/util  
           <context:annotation-config />
           <context:component-scan base-package="com.abin.lee.ssh"></context:component-scan>
           
           <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"       
                  destroy-method="close">      
              <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>      
              <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe"/>      
              <property name="user" value="abin"/>      
              <property name="password" value="abin"/>      
           </bean>
           
           <bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource">
             <ref bean="dataSource" />
            </property>
            <property name="hibernateProperties">
             <props>
              <prop key="hibernate.dialect">
               org.hibernate.dialect.OracleDialect
              </prop>
              <prop key="hibernate.show_sql">
               true
              </prop>
              <prop key="hibernate.show_sql">true</prop>
              <prop key="hibernate.format_sql">true</prop>
              <prop key="hibernate.hbm2ddl.auto">update</prop>
             </props>
            </property>
            <!--主鍵Bean類
            <property name="annotatedClasses">
             <list>
              <value>com.abin.lee.ssh.entity.ModeBean</value>
             </list>
            </property>
             -->
            <!-- 自動掃描-->
             <property name="packagesToScan" value="com.abin.lee.ssh.entity" />
           </bean>
           
           <!-- 配置事務(wù)管理器 -->
           <bean id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory">
             <ref bean="sessionFactory" />
            </property>
           </bean>
           
           <!-- 配置注解實現(xiàn)管理事務(wù)(cglib:proxy-target-class="true") -->
           <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
           <!-- 指定使用cglib -->
           <!--   -->
           <aop:aspectj-autoproxy proxy-target-class="true" />
           
           <!-- 配置事務(wù)的傳播特性 -->
           <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
             <tx:method name="save*" propagation="REQUIRED" />
             <tx:method name="insert*" propagation="REQUIRED" />
             <tx:method name="update*" propagation="REQUIRED" />
             <tx:method name="delete*" propagation="REQUIRED" />
             <tx:method name="*" read-only="false" />
            </tx:attributes>
           </tx:advice>
           
           <!-- 那些類的哪些方法參與事務(wù)-->
           <aop:config>
            <aop:pointcut id="allServiceMethod" expression="execution(* com.abin.lee.ssh.spring.*.*(..))" />
            <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
           </aop:config>
           
          </beans>



          //FastJsonAbstractHttpMessageConverter.java

          package com.abin.lee.ssh.function;

          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.OutputStream;
          import java.net.URLDecoder;
          import java.nio.charset.Charset;

          import org.springframework.http.HttpInputMessage;
          import org.springframework.http.HttpOutputMessage;
          import org.springframework.http.MediaType;
          import org.springframework.http.converter.AbstractHttpMessageConverter;
          import org.springframework.http.converter.HttpMessageNotReadableException;
          import org.springframework.http.converter.HttpMessageNotWritableException;
          import org.springframework.util.FileCopyUtils;

          import com.alibaba.fastjson.JSON;
          import com.alibaba.fastjson.serializer.SerializerFeature;

          //來對requestbody 或responsebody中的數(shù)據(jù)進行解析
          public class FastJsonAbstractHttpMessageConverter extends AbstractHttpMessageConverter<Object>{
            public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
           // fastjson特性參數(shù) 
              private SerializerFeature[] serializerFeature; 
           
              public SerializerFeature[] getSerializerFeature() { 
                  return serializerFeature; 
              } 
           
              public void setSerializerFeature(SerializerFeature[] serializerFeature) { 
                  this.serializerFeature = serializerFeature; 
              } 
           
           //限定頁面文本傳送類型 只有數(shù)據(jù)是改類型 的 才會進行攔截
           //application/json
           public FastJsonAbstractHttpMessageConverter(){
          //  super(new MediaType("text","plain"));
            super(new MediaType("application","json"));
           }
           @Override
           protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputmessage) throws IOException,
             HttpMessageNotReadableException {
            Charset charset;
            MediaType mediaType=inputmessage.getHeaders().getContentType();
            if(mediaType!=null&&mediaType.getCharSet()!=null){
             charset=mediaType.getCharSet();
            }else{
             charset=Charset.forName("UTF-8");
            }
            
            String input=FileCopyUtils.copyToString(new InputStreamReader(inputmessage.getBody(),charset));
            String result=URLDecoder.decode(input, "UTF-8");
            System.out.println(result);
            /*OrgnizationPO po=new OrgnizationPO();
            po.setId(1);
            po.setName("11");
            po.setOrgdesc("1");*/
            
            /*ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
                  int i; 
                  while ((i = inputmessage.getBody().read()) != -1) { 
                      baos.write(i); 
                  }  */
                  return JSON.parseObject(result, clazz);
          //        return JSON.parseArray(baos.toString(), clazz);
          //  return po;
           }

           @Override
           protected boolean supports(Class<?> clazz) {
            return true;
            //throw new UnsupportedOperationException();
           }

           @Override
           protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
             HttpMessageNotWritableException {
            String jsonString = JSON.toJSONString(o, serializerFeature); 
          //  System.out.println(jsonString);
                  OutputStream out = outputMessage.getBody(); 
                  out.write(jsonString.getBytes(DEFAULT_CHARSET)); 
                  out.flush(); 
           }

          }






          package com.abin.lee.ssh.hibernate;

          import com.abin.lee.ssh.entity.ModeBean;

          public interface ModeDao {
           public boolean insert(ModeBean mode);
          }




          package com.abin.lee.ssh.hibernate.impl;

          import javax.annotation.Resource;

          import org.hibernate.SessionFactory;
          import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
          import org.springframework.stereotype.Repository;

          import com.abin.lee.ssh.entity.ModeBean;
          import com.abin.lee.ssh.hibernate.ModeDao;
          @Repository
          public class ModeDaoImpl extends HibernateDaoSupport implements ModeDao{
           
           @Resource(name = "sessionFactory")
           public void setSuperSessionFactory(SessionFactory sessionFactory) {
            super.setSessionFactory(sessionFactory);
           }
           
           public boolean insert(ModeBean mode) {
            boolean flag=false;
            try {
             this.getHibernateTemplate().saveOrUpdate(mode);
             flag=true;
            } catch (Exception e) {
             e.printStackTrace();
            }
            return flag;
           }
           
           
          }






          package com.abin.lee.ssh.spring;

          import com.abin.lee.ssh.entity.ModeBean;

          public interface ModeService {
           public boolean insert(ModeBean mode);

          }





          package com.abin.lee.ssh.spring.impl;

          import javax.annotation.Resource;

          import org.springframework.stereotype.Service;
          import org.springframework.transaction.annotation.Isolation;
          import org.springframework.transaction.annotation.Propagation;
          import org.springframework.transaction.annotation.Transactional;

          import com.abin.lee.ssh.entity.ModeBean;
          import com.abin.lee.ssh.hibernate.ModeDao;
          import com.abin.lee.ssh.spring.ModeService;

          @Service
          @Transactional(readOnly = true, timeout = 2, propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
          public class ModeServiceImpl implements ModeService {
           @Resource
           private ModeDao modeDao;

           @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
           public boolean insert(ModeBean mode) {
            boolean flag = false;
            try {
             flag = this.modeDao.insert(mode);
            } catch (Exception e) {
             e.printStackTrace();
            }
            return flag;
           }

          }






          package com.abin.lee.ssh.springmvc;

          import javax.annotation.Resource;

          import org.springframework.stereotype.Controller;
          import org.springframework.web.bind.annotation.ModelAttribute;
          import org.springframework.web.bind.annotation.RequestMapping;
          import org.springframework.web.bind.annotation.RequestMethod;
          import org.springframework.web.bind.annotation.ResponseBody;

          import com.abin.lee.ssh.dto.request.ModeRequest;
          import com.abin.lee.ssh.dto.response.ModeResponse;
          import com.abin.lee.ssh.entity.ModeBean;
          import com.abin.lee.ssh.spring.ModeService;

          @Controller
          @RequestMapping("/stevenjohn/")
          public class ModeController {
           @Resource
           private ModeService modeService;

           @RequestMapping(value = "getMode", method = RequestMethod.POST)
           public @ResponseBody
           ModeResponse getMode(
             @ModelAttribute ModeRequest modeRequest) {
            ModeResponse response = new ModeResponse();
            String id=modeRequest.getId();
            String username=modeRequest.getUsername();
            String password=modeRequest.getPassword();
            int age=modeRequest.getAge();
            String address=modeRequest.getAddress();
            String email=modeRequest.getEmail();
            ModeBean mode=new ModeBean(id, username, password, age, address, email);
            boolean flag=modeService.insert(mode);
            System.out.println("flag="+flag);
            if(flag==true){
             response.setStatus("success");
            }else{
             response.setStatus("failure");
            }
            
            return response;
           }
          }




          package com.abin.lee.ssh.entity;

          import java.io.Serializable;

          import javax.persistence.Column;
          import javax.persistence.Entity;
          import javax.persistence.Id;
          import javax.persistence.Table;
          @Entity
          @Table(name="MODEBEAN")
          public class ModeBean implements Serializable{
           @Id
           @Column(name="ID")
           private String id;
           @Column(name="USERNAME",length=100,nullable=true)
           private String username;
           @Column(name="PASSWORD",length=100,nullable=true)
           private String password;
           @Column(name="AGE",length=10,nullable=true)
           private int age;
           @Column(name="ADDRESS",length=100,nullable=true)
           private String address;
           @Column(name="EMAIL",length=100,nullable=true)
           private String email;
           public ModeBean() {
           }
           public ModeBean(String id, String username, String password, int age,
             String address, String email) {
            super();
            this.id = id;
            this.username = username;
            this.password = password;
            this.age = age;
            this.address = address;
            this.email = email;
           }
           
           public String getId() {
            return id;
           }
           public void setId(String id) {
            this.id = id;
           }
           public String getUsername() {
            return username;
           }
           public void setUsername(String username) {
            this.username = username;
           }
           public String getPassword() {
            return password;
           }
           public void setPassword(String password) {
            this.password = password;
           }
           public int getAge() {
            return age;
           }
           public void setAge(int age) {
            this.age = age;
           }
           public String getAddress() {
            return address;
           }
           public void setAddress(String address) {
            this.address = address;
           }
           public String getEmail() {
            return email;
           }
           public void setEmail(String email) {
            this.email = email;
           }
           
           
          }







          //SpringMVC請求參數(shù)

          package com.abin.lee.ssh.dto.request;

          import java.io.Serializable;

          public class ModeRequest implements Serializable{
           /**
            *
            */
           private static final long serialVersionUID = 1886596479119297989L;
           private String id;
           private String username;
           private String password;
           private int age;
           private String address;
           private String email;
           public String getId() {
            return id;
           }
           public void setId(String id) {
            this.id = id;
           }
           public String getUsername() {
            return username;
           }
           public void setUsername(String username) {
            this.username = username;
           }
           public String getPassword() {
            return password;
           }
           public void setPassword(String password) {
            this.password = password;
           }
           public int getAge() {
            return age;
           }
           public void setAge(int age) {
            this.age = age;
           }
           public String getAddress() {
            return address;
           }
           public void setAddress(String address) {
            this.address = address;
           }
           public String getEmail() {
            return email;
           }
           public void setEmail(String email) {
            this.email = email;
           }
           
          }





          //SpringMVC響應(yīng)參數(shù)


          package com.abin.lee.ssh.dto.response;

          import java.io.Serializable;

          public class ModeResponse implements Serializable{
           /**
            *
            */
           private static final long serialVersionUID = 7725619232731203410L;
           private String status;
           private String message;
           public ModeResponse() {
           }
           public ModeResponse(String status, String message) {
            super();
            this.status = status;
            this.message = message;
           }
           public String getStatus() {
            return status;
           }
           public void setStatus(String status) {
            this.status = status;
           }
           public String getMessage() {
            return message;
           }
           public void setMessage(String message) {
            this.message = message;
           }
           
          }




          //log4j.properties

          log4j.rootCategory=info,log,console

          log4j.logger.org.apache.axis2.enterprise=FATAL
          log4j.logger.de.hunsicker.jalopy.io=FATAL
          log4j.logger.httpclient.wire.header=FATAL
          log4j.logger.org.apache.commons.httpclient=FATAL

          log4j.appender.console=org.apache.log4j.ConsoleAppender
          log4j.appender.console.layout=org.apache.log4j.PatternLayout
          log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
           
          log4j.appender.log=org.apache.log4j.DailyRollingFileAppender
          log4j.appender.log.File=../logs/mms.log
          log4j.appender.log.layout=org.apache.log4j.PatternLayout
          log4j.appender.log.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n








          //測試springMVC的Junit4+httpClient類:

          package com.abin.lee.ssm;

          import java.io.BufferedReader;
          import java.io.InputStreamReader;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.UUID;

          import junit.framework.TestCase;

          import org.apache.http.HttpResponse;
          import org.apache.http.NameValuePair;
          import org.apache.http.client.HttpClient;
          import org.apache.http.client.entity.UrlEncodedFormEntity;
          import org.apache.http.client.methods.HttpPost;
          import org.apache.http.impl.client.DefaultHttpClient;
          import org.apache.http.message.BasicNameValuePair;
          import org.apache.http.protocol.HTTP;
          import org.junit.Test;

          public class HttpsClient extends TestCase {
           private String httpUrl = "
          http://localhost:7000/universal/mvc/stevenjohn/getMode";

           @Test
           public void testHttpsClient() {
            try {
             HttpClient httpClient = new DefaultHttpClient();
             HttpPost httpPost = new HttpPost(httpUrl);
             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
             nvps.add(new BasicNameValuePair("id", UUID.randomUUID().toString()));
             nvps.add(new BasicNameValuePair("username", "abin"));
             nvps.add(new BasicNameValuePair("password", "abing"));
             nvps.add(new BasicNameValuePair("age", "28"));
             nvps.add(new BasicNameValuePair("address", "beijing of china"));
             nvps.add(new BasicNameValuePair("email", "varyall@tom.com"));
             httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
             HttpResponse httpResponse = httpClient.execute(httpPost);
             BufferedReader buffer = new BufferedReader(new InputStreamReader(
               httpResponse.getEntity().getContent()));
             StringBuffer stb=new StringBuffer();
             String line=null;
             while((line=buffer.readLine())!=null){
              stb.append(line);
             }
             buffer.close();
             String result=stb.toString();
             System.out.println("result="+result);
            } catch (Exception e) {
             e.printStackTrace();
            }

           }

          }

          posted @ 2012-10-21 01:12 abin 閱讀(3950) | 評論 (1)編輯 收藏

          //生成xml文件
          package lc.abin.lee.xml.dom4j;

          import java.io.FileWriter;

          import org.dom4j.Document;
          import org.dom4j.DocumentHelper;
          import org.dom4j.Element;
          import org.dom4j.io.OutputFormat;
          import org.dom4j.io.XMLWriter;

          public class CreateDom4j {
           public static String createXml() throws Exception{
            Document document=DocumentHelper.createDocument();
            Element root=document.addElement("lee");
            Element country=root.addElement("abin");
            Element area=country.addElement("name");
            Element first=area.addElement("lc1");
            first.addText("lc1name");
            Element middle=area.addElement("lc2");
            middle.addText("lc2name");
            Element last=area.addElement("lc3");
            last.addText("lc3name");
            
            FileWriter fileWriter=new FileWriter("lbin.xml");
            OutputFormat format=new OutputFormat();
            format.setEncoding("UTF-8");
            XMLWriter writer=new XMLWriter(fileWriter, format);
            writer.write(document);
            writer.flush();
            writer.close();
            return document.asXML();
           }
           public static void main(String[] args)throws Exception {
            String result=createXml();
            System.out.println("result="+result);
           }
          }

          生成的XML文件內(nèi)容
          <?xml version="1.0" encoding="UTF-8"?>
          <lee><abin><name><lc1>lc1name</lc1><lc2>lc2name</lc2><lc3>lc3name</lc3></name></abin></lee>





          //DOM4J解析XML文件

          package lc.abin.lee.xml.dom4j;

          import java.io.File;
          import java.util.Collections;
          import java.util.HashMap;
          import java.util.Iterator;
          import java.util.List;
          import java.util.Map;

          import org.dom4j.Document;
          import org.dom4j.DocumentException;
          import org.dom4j.Element;
          import org.dom4j.io.SAXReader;

          public class ParseJdom {
           public static Map<String,String> parse(File file) throws DocumentException{
            Map<String,String> map=Collections.synchronizedMap(new HashMap<String,String>());
            SAXReader sax=new SAXReader();
            Document doc=sax.read(file);
            List list=doc.selectNodes("/lee/abin/name");
            for(Iterator it=list.iterator();it.hasNext();){
             Element ele=(Element)it.next();
             for(Iterator its=ele.elementIterator();its.hasNext();){
              Element le=(Element)its.next();
              map.put(le.getName(), le.getText());
              System.out.println("le.getName()="+le.getName());
              System.out.println("le.getText()="+le.getText());
             }
             
            }
            return map;
           }
           public static void main(String[] args) throws Exception {
            File file=new File("lbin.xml");
            Map<String,String> map=parse(file);
            for(Iterator it=map.entrySet().iterator();it.hasNext();){
             Map.Entry entry=(Map.Entry)it.next();
             System.out.println("name="+entry.getKey());
             System.out.println("value="+entry.getValue());
             
            }
           }

          }

           

          posted @ 2012-10-20 21:01 abin 閱讀(532) | 評論 (0)編輯 收藏

          package com.abin.lee.apache;

          import java.lang.reflect.InvocationTargetException;

          import org.apache.commons.beanutils.BeanUtils;

          import com.abin.lee.apache.bean.AirBean;
          import com.abin.lee.apache.bean.SkyBean;

          public class ApacheBeanUtils {
           public static void main(String[] args) throws Exception {
            AirBean air=new AirBean();
            BeanUtils.setProperty(air, "id", "1");
            BeanUtils.setProperty(air, "name", "abin");
            
            SkyBean sky=new SkyBean();
            BeanUtils.copyProperties(sky, air);
            
          //  String id=BeanUtils.getProperty(sky, "id");
          //  String name=BeanUtils.getProperty(sky, "name");
          //  System.out.println("id="+id);
          //  System.out.println("name="+name);
            System.out.println("id="+sky.getId());
            System.out.println("name="+sky.getName());
            System.out.println("name="+sky.getClass());
           }

          }

          posted @ 2012-10-19 12:50 abin 閱讀(573) | 評論 (0)編輯 收藏

               摘要: 功能說明: 顧名思義,Bean Utility就是Bean小工具,主要是封裝了反射(reflection)和自?。╥ntrospection)的API(可以查看java.lang.reflect和java.beans文檔),對bean進行操作。主要功能: 操作Bean的屬性,針對Bean屬性排序,Bean和Map的轉(zhuǎn)換,創(chuàng)建動態(tài)的Bean等 Apache提供的架包:c...  閱讀全文
          posted @ 2012-10-18 13:39 abin 閱讀(1695) | 評論 (0)編輯 收藏

          Volatile修飾的成員變量在每次被線程訪問時,都強迫從共享內(nèi)存中重讀該成員變量的值。而且,當成員變量發(fā)生變化時,強迫線程將變化值回寫到共享內(nèi)存。這樣在任何時刻,
          兩個不同的線程總是看到某個成員變量的同一個值。
          
          Java語言規(guī)范中指出:為了獲得最佳速度,允許線程保存共享成員變量的私有拷貝,而且只當線程進入或者離開同步代碼塊時才與共享成員變量的原始值對比。
          
          這樣當多個線程同時與某個對象交互時,就必須要注意到要讓線程及時的得到共享成員變量的變化。
          
          而volatile關(guān)鍵字就是提示VM:對于這個成員變量不能保存它的私有拷貝,而應(yīng)直接與共享成員變量交互。
          
          使用建議:在兩個或者更多的線程訪問的成員變量上使用volatile。當要訪問的變量已在synchronized代碼塊中,或者為常量時,不必使用。
          
          由于使用volatile屏蔽掉了VM中必要的代碼優(yōu)化,所以在效率上比較低,因此一定在必要時才使用此關(guān)鍵字。 
          
          
          就跟C中的一樣 禁止編譯器進行優(yōu)化~~~~
          在并發(fā)中可保證內(nèi)存一致性
          volatile聲明的變量只在主存中存儲
          讀取的時候,會有讀取臟數(shù)據(jù)的情況發(fā)生
          但是寫數(shù)據(jù)的時候,是能保證數(shù)據(jù)能正確寫入

          volatile只保證每次都從主存拿數(shù)據(jù),其他保證不了什么吧?
          告訴編譯器不要使用緩存

          非long、double變量不能保證原子性,非volatile變量不能保證內(nèi)存可見性。

          volatile 還能防止reorder...
          就是內(nèi)存屏蔽,防止指令重拍
          其實目的就是保證可見性
          可以操作volatile...變量 但是不代表你的操作指令是原子的








          posted @ 2012-10-18 10:38 abin 閱讀(344) | 評論 (0)編輯 收藏

          在java線程并發(fā)處理中,有一個關(guān)鍵字volatile的使用目前存在很大的混淆,以為使用這個關(guān)鍵字,在進行多線程并發(fā)處理的時候就可以萬事大吉。

          Java語言是支持多線程的,為了解決線程并發(fā)的問題,在語言內(nèi)部引入了 同步塊 和 volatile 關(guān)鍵字機制。

           

          synchronized 

          同步塊大家都比較熟悉,通過 synchronized 關(guān)鍵字來實現(xiàn),所有加上synchronized 和 塊語句,在多線程訪問的時候,同一時刻只能有一個線程能夠用

          synchronized 修飾的方法 或者 代碼塊。

           

          volatile

          用volatile修飾的變量,線程在每次使用變量的時候,都會讀取變量修改后的最的值。volatile很容易被誤用,用來進行原子性操作。

           

          下面看一個例子,我們實現(xiàn)一個計數(shù)器,每次線程啟動的時候,會調(diào)用計數(shù)器inc方法,對計數(shù)器進行加一

           

          執(zhí)行環(huán)境——jdk版本:jdk1.6.0_31 ,內(nèi)存 :3G   cpu:x86 2.4G

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          public class Counter {
            
              public static int count = 0;
            
              public static void inc() {
            
                  //這里延遲1毫秒,使得結(jié)果明顯
                  try {
                      Thread.sleep(1);
                  } catch (InterruptedException e) {
                  }
            
                  count++;
              }
            
              public static void main(String[] args) {
            
                  //同時啟動1000個線程,去進行i++計算,看看實際結(jié)果
            
                  for (int i = 0; i < 1000; i++) {
                      new Thread(new Runnable() {
                          @Override
                          public void run() {
                              Counter.inc();
                          }
                      }).start();
                  }
            
                  //這里每次運行的值都有可能不同,可能為1000
                  System.out.println("運行結(jié)果:Counter.count=" + Counter.count);
              }
          }
          1
            
          1
          運行結(jié)果:Counter.count=995
          1
          實際運算結(jié)果每次可能都不一樣,本機的結(jié)果為:運行結(jié)果:Counter.count=995,可以看出,在多線程的環(huán)境下,Counter.count并沒有期望結(jié)果是1000
          1
            
          1
          很多人以為,這個是多線程并發(fā)問題,只需要在變量count之前加上volatile就可以避免這個問題,那我們在修改代碼看看,看看結(jié)果是不是符合我們的期望
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          public class Counter {
            
              public volatile static int count = 0;
            
              public static void inc() {
            
                  //這里延遲1毫秒,使得結(jié)果明顯
                  try {
                      Thread.sleep(1);
                  } catch (InterruptedException e) {
                  }
            
                  count++;
              }
            
              public static void main(String[] args) {
            
                  //同時啟動1000個線程,去進行i++計算,看看實際結(jié)果
            
                  for (int i = 0; i < 1000; i++) {
                      new Thread(new Runnable() {
                          @Override
                          public void run() {
                              Counter.inc();
                          }
                      }).start();
                  }
            
                  //這里每次運行的值都有可能不同,可能為1000
                  System.out.println("運行結(jié)果:Counter.count=" + Counter.count);
              }
          }

          運行結(jié)果:Counter.count=992

          運行結(jié)果還是沒有我們期望的1000,下面我們分析一下原因

           

          在 java 垃圾回收整理一文中,描述了jvm運行時刻內(nèi)存的分配。其中有一個內(nèi)存區(qū)域是jvm虛擬機棧,每一個線程運行時都有一個線程棧,

          線程棧保存了線程運行時候變量值信息。當線程訪問某一個對象時候值的時候,首先通過對象的引用找到對應(yīng)在堆內(nèi)存的變量的值,然后把堆內(nèi)存

          變量的具體值load到線程本地內(nèi)存中,建立一個變量副本,之后線程就不再和對象在堆內(nèi)存變量值有任何關(guān)系,而是直接修改副本變量的值,

          在修改完之后的某一個時刻(線程退出之前),自動把線程變量副本的值回寫到對象在堆中變量。這樣在堆中的對象的值就產(chǎn)生變化了。下面一幅圖

          描述這寫交互

           

          java volatile1

           

           

          read and load 從主存復(fù)制變量到當前工作內(nèi)存
          use and assign  執(zhí)行代碼,改變共享變量值
          store and write 用工作內(nèi)存數(shù)據(jù)刷新主存相關(guān)內(nèi)容

          其中use and assign 可以多次出現(xiàn)

          但是這一些操作并不是原子性,也就是 在read load之后,如果主內(nèi)存count變量發(fā)生修改之后,線程工作內(nèi)存中的值由于已經(jīng)加載,不會產(chǎn)生對應(yīng)的變化,所以計算出來的結(jié)果會和預(yù)期不一樣

          對于volatile修飾的變量,jvm虛擬機只是保證從主內(nèi)存加載到線程工作內(nèi)存的值是最新的

          例如假如線程1,線程2 在進行read,load 操作中,發(fā)現(xiàn)主內(nèi)存中count的值都是5,那么都會加載這個最新的值

          在線程1堆count進行修改之后,會write到主內(nèi)存中,主內(nèi)存中的count變量就會變?yōu)?

          線程2由于已經(jīng)進行read,load操作,在進行運算之后,也會更新主內(nèi)存count的變量值為6

          導(dǎo)致兩個線程及時用volatile關(guān)鍵字修改之后,還是會存在并發(fā)的情況。

          愛公司的程序員
          博客園blog地址:http://www.cnblogs.com/aigongsi/
          本人版權(quán)歸作者和博客園所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明出處。

          posted @ 2012-10-18 10:38 abin 閱讀(293) | 評論 (0)編輯 收藏

          1、首先建表:
          create table tababin(
          id int not null auto_increment,
          name varchar(100),
          constraint pk primary key(id)
          )

          2、拷貝一張相同的表:
          create table tababin1 like tababin;

          3.建立主鍵自增觸發(fā)器:
          create trigger triabin before insert on tababin for each ROW
          begin
          set @new=new.id;
          end

          4、插入記錄:
          insert into tababin (name) values ('abin1')
          insert into tababin (name) values ('abin2')
          insert into tababin (name) values ('abin3')

          5‘編寫存儲過程(帶游標和LOOP循環(huán)的存儲過程):
          CREATE  PROCEDURE pabin()
          begin
          declare id,status int ;
          declare name varchar(100);
          declare mycur cursor for select * from tababin;
          declare continue handler for not found set status=1;
          open mycur;
          set status=0;
          loopLabel:loop
          fetch mycur into id,name;
          if status=0 then
          if id is not null then
          if name is not null then
          insert into tababin1 values (id,name);
          end if;
          end if;
          end if;
          if status =1 then
          leave loopLabel;
          end if;
          end loop;
          close mycur;
          end

          6、測試存儲過程:
          call pabin()


          結(jié)果:tababin1表里面新增了數(shù)據(jù)。
          posted @ 2012-10-18 10:21 abin 閱讀(462) | 評論 (0)編輯 收藏

          僅列出標題
          共50頁: First 上一頁 24 25 26 27 28 29 30 31 32 下一頁 Last 
          主站蜘蛛池模板: 建德市| 开平市| 阜南县| 星子县| 绵竹市| 仙居县| 衡阳县| 白山市| 佛山市| 东源县| 东丰县| 射阳县| 夏津县| 成武县| 沭阳县| 齐齐哈尔市| 福州市| 金溪县| 盘山县| 阿克| 本溪| 富宁县| 万宁市| 新沂市| 秦皇岛市| 河西区| 北海市| 进贤县| 苗栗县| 凤冈县| 西贡区| 河南省| 阆中市| 鹿泉市| 康定县| 巫溪县| 琼中| 蓝山县| 三台县| 凤翔县| 华池县|