<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    少年阿賓

    那些青春的歲月

      BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
      500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

    #

    蝦米(354668137)  11:17:35
    memcached的數據怎么與數據庫的數據保持同步啊??
    南京-HF(226358522)  11:18:04
    手動同步
    南京-HF(226358522)  11:18:06
    代碼實現
    滄海長風(136419390)  11:18:12
    兩邊同時寫
    滄海長風(136419390)  11:18:31
    或者定期寫
    滄海長風(136419390)  11:18:35
    或者特定條件寫
    蝦米(354668137)  11:19:23
    額,memcached沒有提供相關的支持嗎
    南京-HF(226358522)  11:20:30
    有個對mysql的同步的庫
    南京-HF(226358522)  11:20:49
    是由mysql同步數據到memcached的
    ζ 過了時的流行 ?(779014475)  11:21:13
    蝦米(354668137)  11:17:35
    memcached的數據怎么與數據庫的數據保持同步啊??
    ζ 過了時的流行 ?(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
    應該是mysql里面有觸發器,當數據有改變,就會同步到memcached
    南京-HF(226358522)  11:23:30
    就看你以哪個數據為主了
    南京-HF(226358522)  11:24:04
    這樣memcached的目的就是加快你的查詢速度
    滄海長風(136419390)  11:24:18
    這方案根據自己需求設定
    滄海長風(136419390)  11:24:23
    組合很多吧
    ζ 過了時的流行 ?(779014475)  11:25:03
    最近也碰到。。mysql與mc同步的。。不知道有啥好方案
    南京-HF(226358522)  11:25:08
    畢竟,查詢用的是最多的。修改或者插入的話,數據庫的數據必須得邊,所以才有這么個方案。當然這個也不一定適合你們的場景,你自己取舍
    南京-HF(226358522)  11:26:21
    如果你的數據,增刪改查都很頻繁那這種就不適合了
    ζ 過了時的流行 ?(779014475)  11:26:54
    恩。。這樣的話讀寫都直接對mc操作。。然后定時同步。。
    ζ 過了時的流行 ?(779014475)  11:27:09
    但是蛋疼的就是同步方案。。


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

    posted @ 2012-10-23 13:19 abin 閱讀(3132) | 評論 (0)編輯 收藏

    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 閱讀(1756) | 評論 (0)編輯 收藏

         摘要: 1、原子性(Atomicity) 事務的原子性是指事務中包含的所有操作要么都做,要么都不做,保證數據庫是一致的。 例如:A帳戶向B帳戶劃賬1000,則先將A減少1000,再將B增加1000,這兩個動作要么都提交,要么都回退,不可能發生一個有效、一個無效的情況。 2、一致性(Consistency) 一致性是指數據庫在事務操作前和事務處理后,其中的數據必須都滿足業務規則約束。 ...  閱讀全文
    posted @ 2012-10-21 16:37 abin 閱讀(3233) | 評論 (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  <!-- 指定系統尋找controller路徑 -->
     <mvc:annotation-driven>
      <!-- json 數據格式轉換-->
      <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>
     
     <!-- 配置事務管理器 -->
     <bean id="transactionManager"
      class="org.springframework.orm.hibernate3.HibernateTransactionManager">
      <property name="sessionFactory">
       <ref bean="sessionFactory" />
      </property>
     </bean>
     
     <!-- 配置注解實現管理事務(cglib:proxy-target-class="true") -->
     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
     <!-- 指定使用cglib -->
     <!--   -->
     <aop:aspectj-autoproxy proxy-target-class="true" />
     
     <!-- 配置事務的傳播特性 -->
     <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>
     
     <!-- 那些類的哪些方法參與事務-->
     <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中的數據進行解析
    public class FastJsonAbstractHttpMessageConverter extends AbstractHttpMessageConverter<Object>{
      public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
     // fastjson特性參數 
        private SerializerFeature[] serializerFeature; 
     
        public SerializerFeature[] getSerializerFeature() { 
            return serializerFeature; 
        } 
     
        public void setSerializerFeature(SerializerFeature[] serializerFeature) { 
            this.serializerFeature = serializerFeature; 
        } 
     
     //限定頁面文本傳送類型 只有數據是改類型 的 才會進行攔截
     //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請求參數

    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響應參數


    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 閱讀(3945) | 評論 (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文件內容
    <?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 閱讀(530) | 評論 (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 閱讀(572) | 評論 (0)編輯 收藏

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

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

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

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

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








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

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

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

     

    synchronized 

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

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

     

    volatile

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

     

    下面看一個例子,我們實現一個計數器,每次線程啟動的時候,會調用計數器inc方法,對計數器進行加一

     

    執行環境——jdk版本:jdk1.6.0_31 ,內存 :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毫秒,使得結果明顯
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
            }
      
            count++;
        }
      
        public static void main(String[] args) {
      
            //同時啟動1000個線程,去進行i++計算,看看實際結果
      
            for (int i = 0; i < 1000; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Counter.inc();
                    }
                }).start();
            }
      
            //這里每次運行的值都有可能不同,可能為1000
            System.out.println("運行結果:Counter.count=" + Counter.count);
        }
    }
    1
      
    1
    運行結果:Counter.count=995
    1
    實際運算結果每次可能都不一樣,本機的結果為:運行結果:Counter.count=995,可以看出,在多線程的環境下,Counter.count并沒有期望結果是1000
    1
      
    1
    很多人以為,這個是多線程并發問題,只需要在變量count之前加上volatile就可以避免這個問題,那我們在修改代碼看看,看看結果是不是符合我們的期望
    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毫秒,使得結果明顯
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
            }
      
            count++;
        }
      
        public static void main(String[] args) {
      
            //同時啟動1000個線程,去進行i++計算,看看實際結果
      
            for (int i = 0; i < 1000; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Counter.inc();
                    }
                }).start();
            }
      
            //這里每次運行的值都有可能不同,可能為1000
            System.out.println("運行結果:Counter.count=" + Counter.count);
        }
    }

    運行結果:Counter.count=992

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

     

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

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

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

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

    描述這寫交互

     

    java volatile1

     

     

    read and load 從主存復制變量到當前工作內存
    use and assign  執行代碼,改變共享變量值
    store and write 用工作內存數據刷新主存相關內容

    其中use and assign 可以多次出現

    但是這一些操作并不是原子性,也就是 在read load之后,如果主內存count變量發生修改之后,線程工作內存中的值由于已經加載,不會產生對應的變化,所以計算出來的結果會和預期不一樣

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

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

    在線程1堆count進行修改之后,會write到主內存中,主內存中的count變量就會變為6

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

    導致兩個線程及時用volatile關鍵字修改之后,還是會存在并發的情況。

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

    posted @ 2012-10-18 10:38 abin 閱讀(291) | 評論 (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.建立主鍵自增觸發器:
    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循環的存儲過程):
    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()


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

    僅列出標題
    共50頁: First 上一頁 24 25 26 27 28 29 30 31 32 下一頁 Last 
    主站蜘蛛池模板: 国产精品亚洲mnbav网站| 免费大片av手机看片| 久久激情亚洲精品无码?V| 成人毛片免费播放| 亚洲黄色免费观看| 青青操免费在线视频| 国产亚洲综合久久| 亚洲中文字幕久久无码| 亚洲综合在线成人一区| 亚洲VA中文字幕无码一二三区 | 亚洲人成在线播放| 97久久精品亚洲中文字幕无码 | 午夜在线亚洲男人午在线| 国产午夜亚洲精品国产| 亚洲成a人不卡在线观看| 亚洲av鲁丝一区二区三区| 亚洲永久无码3D动漫一区| 亚洲日本韩国在线| 亚洲国产av无码精品| 国产zzjjzzjj视频全免费| 狠狠久久永久免费观看| 免费无码黄十八禁网站在线观看| 精品免费人成视频app| 99re在线免费视频| 最近中文字幕免费完整| 在线免费观看国产| 国产精品久久久久久久久免费| 1000部免费啪啪十八未年禁止观看| 免费视频一区二区| 7x7x7x免费在线观看| 最近2018中文字幕免费视频 | 亚洲国产精品午夜电影| 亚洲第一香蕉视频| 亚洲乱码卡一卡二卡三| 丁香婷婷亚洲六月综合色| 亚洲小说图区综合在线| 亚洲午夜精品久久久久久app | 日本中文一区二区三区亚洲| 免费人成激情视频| 亚洲色偷偷综合亚洲AV伊人| 亚洲精品色午夜无码专区日韩|