GVKun编程网logo

TeaFramework——ORM框架的实现(一)(orm框架有哪些优缺点)

22

对于TeaFramework——ORM框架的实现感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解一,并且为您提供关于.NetFramework4.7或仅.NetFramework2.0上的W

对于TeaFramework——ORM框架的实现感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解,并且为您提供关于.Net Framework 4.7或仅.Net Framework 2.0上的Winforms是否兼容Mono?、Entity Framework框架 (一)、org.apache.curator.framework.CuratorFramework的实例源码、org.apache.curator.framework.imps.CuratorFrameworkState的实例源码的宝贵知识。

本文目录一览:

TeaFramework——ORM框架的实现(一)(orm框架有哪些优缺点)

TeaFramework——ORM框架的实现(一)(orm框架有哪些优缺点)

一、实现要求

1、数据访问层的职责是对数据库进行增删改查的操作,所以可以非常单一,仅仅只需要一个inteface即可搞定;

2、全自动ORM不利于SQL的优化与SQL的定制,所以TeaFrameWork  ORM准备用半自动的方式实现,开发人员需要写SQL;

3、告别配置文件,纯注解;

4、接口每个方法只需要一个参数,可以是PO对象、可以是MAP、可以是8大基本数据类型+String和Date

5、动态绑定SQL

6、支持Oracle、Mysql

7、自动分页

8、占位符用#号,如:#id#,#name#,这个和ibatis一致

二、分析

1、设计上ORM只需要inteface,那么具体实现类必须由框架生成,对比了很多字节码生成工具之后,决定采用cglib

2、对数据库的操作,本质上只有两种:读、写。

(1)、读即Select语句,返回值类型:8大基本数据类型+String和Date、PO对象、List<PO对象>、List<Map<String,Object>>,这里我们限定了返回的类型,基本上满足了日常开发

(2)、写:insert、update、delete等,insert操作中有个主键获取问题,可以自动生成,也可以写SQL获得,例如Oracle的select s_users.nextval from dual

三、具体实现

1、注解

(1)、@TeaDao标示这个inteface是数据访问层,让bean容器启动时可以扫描到

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TeaDao {
	public String value() default "";
}

(2)、@SQL给具体方法绑定SQL语句,如:@SQL("select * from users") public List<User> getAllUser();

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SQL {
	public String value();
}

(3)、@GetPrimaryKey注解生成主键的语句,通常和insert语句配合使用

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface GetPrimaryKey {
	public String sql();

	public String primaryKeyProperty();
}

如:

    @GetPrimaryKey(sql = "select s_users.nextval from dual", primaryKeyProperty = "id")
	@SQL("insert into users(id,name,password,createdate) values(#id#,#name#,#password#,#createdate#)")
	public int add(Map<String, Object> map);

(4)、@AutoIncrement注解新增时由数据库自动生成主键,和新增配合使用

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AutoIncrement {

}

(5)、@DynamicSQL注解方法的SQL是动态传入,在查询场景下使用

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DynamicSQL {

}

2、代理类OrmProxy,具体拦截inteface的方式,执行SQL

public class OrmProxy implements InterfaceExecutor {
	private final static String SELECT = "select";
	private final static String INSERT = "insert";

	private static OrmProxy instance;

	private OrmProxy() {
	}

	public synchronized static OrmProxy getInstance() {
		if (instance == null) {
			instance = new OrmProxy();
		}
		return instance;
	}

	@Override
	public Object invoke(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if (method.getDeclaringClass().equals(java.lang.Object.class)) {
			return proxy.invokeSuper(obj, args);
		}
		if (!method.isAnnotationPresent(SQL.class) && !method.isAnnotationPresent(DynamicSQL.class)) {
			throw new TeaOrmException("没有绑定SQL");
		}
		if (args != null && args.length > 1) {
			throw new TeaOrmException("只能传递一个参数");
		}
		if (method.isAnnotationPresent(GetPrimaryKey.class) && method.isAnnotationPresent(AutoIncrement.class)) {
			throw new TeaOrmException("GetPrimaryKey和AutoIncrement不能同时注解在一个方法上");
		}
		if (method.getAnnotation(SQL.class) != null && method.getAnnotation(DynamicSQL.class) != null) {
			throw new TeaOrmException("SQL和DynamicSQL不能同时注解在一个方法上");
		}
		if (TranscationThreadVariable.get() == null || !TranscationThreadVariable.get()) {
			if (ConnectionThreadVariable.getConnetion() == null) {
				ConnectionThreadVariable.setConnetion(DataSourceHelp.getConnection());
			}
		}
		try {
			if (method.isAnnotationPresent(SQL.class)) {
				String sql = method.getAnnotation(SQL.class).value().trim();
				AbstractDataBind dataBind = DataBindFactory
						.getDataBind(args == null || args.length == 0 ? null : args[0]);
				if (!SELECT.equalsIgnoreCase(sql.substring(0, 6))) {
					boolean isAutoIncrement = false;
					if (INSERT.equalsIgnoreCase(sql.substring(0, 6))) {
						if (method.getAnnotation(AutoIncrement.class) != null) {
							isAutoIncrement = true;
						}
						if (method.getAnnotation(GetPrimaryKey.class) != null) {
							Object object = dataBind.fillPrimaryKey(method, args[0]);// 填充主键
							dataBind.excuteUpdate(sql, args == null || args.length == 0 ? null : args[0],
									isAutoIncrement);
							return object;
						}
					}
					return dataBind.excuteUpdate(sql, args == null || args.length == 0 ? null : args[0],
							isAutoIncrement);
				} else {
					return QueryResultProcesser.createQueryResult(
							dataBind.excuteQuery(sql, args == null || args.length == 0 ? null : args[0]), method);
				}
			} else if (method.isAnnotationPresent(DynamicSQL.class)) {
				String sql = DynamicSqlUtil.get() == null ? null : DynamicSqlUtil.get().trim();
				if (null == sql || "".equals(sql)) {
					throw new TeaOrmException("SQL语句不能为空");
				}
				if (sql.length() < 6 || !SELECT.equalsIgnoreCase(sql.substring(0, 6))) {
					throw new TeaOrmException("只能绑定select语句");
				}
				return QueryResultProcesser.createQueryResult(DataBindFactory.getDataBind(null).excuteQuery(sql,
						args == null || args.length == 0 ? null : args[0]), method);
			}
		} catch (Exception e) {
			throw new TeaOrmException(e);
		} finally {
			if (TranscationThreadVariable.get() == null || !TranscationThreadVariable.get()) {
				ConnectionThreadVariable.getConnetion().close();
				ConnectionThreadVariable.clearThreadVariable();
			}
		}
		return null;
	}

}

代码解释:

(1)、用于都是method执行,没有共享变量,所以没有线程安全问题,故而这里用单例模式

(2)、获取SQL分两大块,动态SQL和固定注解SQL,动态SQL只用于查询场景。对于新增,需要获取主键生成方案(sql生成和自动生成)

(3)、InterfaceExecutor接口会在Bean容器设计中详细讲到

(4)、Transcation相关的代码,会在事务设计中详细讲到

自此,一个ORM核心的代码已经完成,剩下SQL的执行过程、占位符替换,请关注《TeaFramework——ORM框架的实现(二)》

 

项目地址:https://git.oschina.net/lxkm/teaframework
博客:https://my.oschina.net/u/1778239/blog 

 

.Net Framework 4.7或仅.Net Framework 2.0上的Winforms是否兼容Mono?

.Net Framework 4.7或仅.Net Framework 2.0上的Winforms是否兼容Mono?

如何解决.Net Framework 4.7或仅.Net Framework 2.0上的Winforms是否兼容Mono??

根据此处的信息https://www.mono-project.com/docs/about-mono/compatibility/,Mono支持Winforms的最高版本(基于哪个.Net Framework)?我认为同一页面上这两个引用中的信息是矛盾的:

“描述Mono当前支持的最简单方法是: .NET 4.7中的所有内容(WPF,WWF除外),以及WCF受限和ASP.NET异步堆栈受限。”据我了解,WWF决定使用Windows Workflow Foundation,因此这意味着Winforms在.Net Frameork 4.7上由Mono支持。这应该很清楚。但是然后:

.NET 2.0复选标记:Winforms / System.Drawing 2.0 ”由于未提及在任何更高版本的.NET上实现的Winforms,这使我认为没有更高版本的Winforms。然后支持.Net Framework 2.0。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Entity Framework框架 (一)

Entity Framework框架 (一)

1. Entity Framework的详细介绍:

Entity Framework简称EF,与Asp.net关系与Ado.net关系。

Entity Framework是ado.net中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架。

ORM:object relation mapping 是基于关系型数据库的数据储备,实现一个模拟的面向对象的数据访问接口,理想情况下,基于这样一个面向对象的接口,持久化一个oo对象应该不需要了解任何关系型数据库存储数据的实现细节。

类似的轻量级的orm框架,dapper,patapoct

 1. lambda表达式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    //定义一个委托
    public delegate int AddSum(int a,int b);
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
           // AddSum addSum = new AddSum(p.Add);
           // AddSum addSum = delegate(int a, int b) { return a + b; };
            //AddSum addSum = (int a, int b) => { return a + b; };
            //简化之后的lambda表达式
            AddSum addSum = ( a,  b) => { return a + b; };
            int sum = addSum(5, 3);
            Console.WriteLine(sum);
            Console.ReadKey();
        }

        //public int Add(int a, int b)
        //{
        //    return a + b;
        //}
    }
    
}
lambda表达式

一、第一种使用EF的方法:先有数据库再建立数据模型

 1. 在项目中右击新建,新建一个ADO.net实体数据模型,选择从数据库生成,这种是先有数据库再建立数据模型的方式。然后依次点击下一步便可,完成以后切记点击ctrl+s保存。不然是不会生成数据模型对应的类。

 2. 注意:对应的数据库表必须有主键,不然在使用时会报错。

 3. 生成之后的结构如下。 

 4.使用EF进行相关的增删改查代码如下:

 新建的web窗体页面,分别放四个button按钮便可。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 
  8 namespace WebApplication2
  9 {
 10     public partial class WebForm1 : System.Web.UI.Page
 11     {
 12         protected void Page_Load(object sender, EventArgs e)
 13         {
 14 
 15         }
 16         /// <summary>
 17         /// 插入数据
 18         /// </summary>
 19         /// <param name="sender"></param>
 20         /// <param name="e"></param>
 21         protected void Button1_Click(object sender, EventArgs e)
 22         {
 23             UserInfo UserInfo = new UserInfo();
 24             UserInfo.UserName = "张五呀";
 25             UserInfo.UserPass = "123qwe";
 26             UserInfo.RegTime = 2;
 27             UserInfo.Email = "wangjin";
 28             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 29             //将数据添加到EF中,并且添加了标记,并且类似于生成了一条insert语句,但是这时候还没有执行该语句
 30             db.UserInfo.Add(UserInfo);
 31             //之后执行该代码时,才会执行insert语句,并且返回受影响行数
 32             db.SaveChanges();
 33             //返回刚刚插入的主键ID
 34             Response.Write(UserInfo.ID);
 35         }
 36         /// <summary>
 37         /// 查询数据
 38         /// </summary>
 39         /// <param name="sender"></param>
 40         /// <param name="e"></param>
 41         protected void Button2_Click(object sender, EventArgs e)
 42         {
 43             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 44             var userinfolist = from u in db.UserInfo   //linq表达式
 45                                where u.ID == 65 
 46                                select u;
 47             //EF的延迟加载机制,只有数据在使用的时候才会去数据库中查询,不用的时候不查询。
 48             //只有执行下面的代码的时候才会去执行,这样可以提高整体的性能
 49             foreach (var userinfo in userinfolist)
 50             {
 51                 Response.Write(userinfo.ID);
 52             }
 53             //FirstOrDefault  查询第一条数据或者查询默认值
 54             //userinfolist.FirstOrDefault();
 55         }
 56         /// <summary>
 57         /// 删除数据
 58         /// </summary>
 59         /// <param name="sender"></param>
 60         /// <param name="e"></param>
 61         protected void Button3_Click(object sender, EventArgs e)
 62         {
 63             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 64             var userinfolist = from u in db.UserInfo
 65                                where u.ID == 66
 66                                select u;
 67             //返回第一条数据,如果没有就放回null
 68             UserInfo userinfo = userinfolist.FirstOrDefault();
 69             if (userinfo != null)
 70             {
 71                 db.UserInfo.Remove(userinfo);
 72                 db.SaveChanges();
 73                 Response.Write("删除成功");
 74             }
 75             else
 76             {
 77                 Response.Write("数据有误");
 78             }
 79             
 80             ////执行删除的第二种方法
 81             //UserInfo userInfo = new UserInfo() {ID=344};
 82             db.Entry<UserInfo>(userinfo).State = System.Data.Entity.EntityState.Deleted;
 83             //db.SaveChanges();
 84         }
 85 
 86         /// <summary>
 87         /// 修改数据
 88         /// </summary>
 89         /// <param name="sender"></param>
 90         /// <param name="e"></param>
 91         protected void Button4_Click(object sender, EventArgs e)
 92         {
 93             //构建一个
 94             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 95             var userinfolist = from u in db.UserInfo
 96                                where u.ID == 65
 97                                select u;
 98             UserInfo userinfo = userinfolist.FirstOrDefault();
 99             userinfo.UserPass = "qweqwe";
100             db.Entry<UserInfo>(userinfo).State = System.Data.Entity.EntityState.Modified;
101             db.SaveChanges();
102             Response.Write("修改成功");
103         }
104     }
105 }

 

 二、第二种ModelFirst模式使用EF的方法,先建立数据模型,再生成数据库对应的表。

 1. 先在数据库中新建一个数据库。

 2.  在项目中右击新建项目,选择数据源,点击空模型。

 3. 在生成的空白界面中,右击新增实体,新增之后再新增标量属性,如果是多表,并且有关联的表,右击新增关联,再右击根据数据模型生成数据库。

 4. 点击如下文件,需要点击执行才会生成数据库。

 5. 使用第二种进行增删改查的相关代码如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 
  8 namespace WebApplication1
  9 {
 10     public partial class WebForm2 : System.Web.UI.Page
 11     {
 12         protected void Page_Load(object sender, EventArgs e)
 13         {
 14 
 15         }
 16         /// <summary>
 17         /// 插入数据
 18         /// </summary>
 19         /// <param name="sender"></param>
 20         /// <param name="e"></param>
 21         protected void Button1_Click(object sender, EventArgs e)
 22         {
 23             Model2Container db = new Model2Container();
 24             Customer customer = new Customer() {CustomerName="zhangsan",CustomerPwd="123", SubTime=DateTime.Now };
 25             // Customer = customer导航属性,代表下面的数据属于上面的值
 26             OrderInfo orderInfo1 = new OrderInfo() { ID = Guid.NewGuid(), OrderNum = "10001", CreateDateTime = DateTime.Now,Customer=customer };
 27             OrderInfo orderInfo2 = new OrderInfo() { ID = Guid.NewGuid(), OrderNum = "10002", CreateDateTime = DateTime.Now, Customer = customer };
 28             db.Customer.Add(customer);
 29             db.OrderInfo.Add(orderInfo1);
 30             db.OrderInfo.Add(orderInfo2);
 31             db.SaveChanges();//默认的已经开启了事务。 工作单元模式。(UnitOfwork)
 32         }
 33         /// <summary>
 34         /// 查询数据
 35         /// </summary>
 36         /// <param name="sender"></param>
 37         /// <param name="e"></param>
 38         protected void Button2_Click(object sender, EventArgs e)
 39         {
 40             Model2Container db = new Model2Container();
 41             var customerList = from c in db.Customer
 42                                select c;
 43             foreach (var customer in customerList)
 44             {
 45                 Response.Write(customer.CustomerName+":");
 46 
 47 
 48                 foreach (var orderInfo in customer.OrderInfo)//延迟加载。
 49                 {
 50                     Response.Write(orderInfo.OrderNum);
 51                 }
 52             }
 53         }
 54         /// <summary>
 55         /// 根据名字id查询所有的订单
 56         /// </summary>
 57         /// <param name="sender"></param>
 58         /// <param name="e"></param>
 59         protected void Button3_Click(object sender, EventArgs e)
 60         {
 61             Model2Container db = new Model2Container();
 62             //var customerInfoList = from c in db.Customer
 63             //                   where c.ID == 1
 64             //                   select c;
 65             //var customerInfo = customerInfoList.FirstOrDefault();
 66             //foreach (var orderInfo in customerInfo.OrderInfo)
 67             //{
 68             //    Response.Write(orderInfo.OrderNum);
 69             //}
 70 
 71             var orderInfoList = from o in db.OrderInfo
 72                                where o.CustomerID == 1
 73                                select o;
 74             foreach (var orderInfo in orderInfoList)
 75             {
 76                 Response.Write(orderInfo.OrderNum);
 77             }
 78                            
 79         }
 80         /// <summary>
 81         /// 输出10001对应的客户ID
 82         /// </summary>
 83         /// <param name="sender"></param>
 84         /// <param name="e"></param>
 85         protected void Button4_Click(object sender, EventArgs e)
 86         {
 87              Model2Container db = new Model2Container();
 88              var orderInfoList = from o in db.OrderInfo
 89                                  where o.OrderNum == "10001"
 90                                  select o;
 91              var orderInfo = orderInfoList.FirstOrDefault();
 92              Customer customer = orderInfo.Customer;
 93              Response.Write(customer.CustomerName);
 94         }
 95         /// <summary>
 96         /// 根据人员ID删除对应数据
 97         /// </summary>
 98         /// <param name="sender"></param>
 99         /// <param name="e"></param>
100         protected void Button5_Click(object sender, EventArgs e)
101         {
102             Model2Container db = new Model2Container();
103             //var customer = (from c in db.Customer
104             //                where c.ID == 1
105             //                select c).FirstOrDefault();
106             //var orderInfoList = customer.OrderInfo;
107             //while (orderInfoList.Count > 0)
108             //{
109             //    var orderInfo = orderInfoList.FirstOrDefault();
110             //    db.Entry<OrderInfo>(orderInfo).State = System.Data.EntityState.Deleted;
111             //}
112             //db.SaveChanges();
113 
114             var orderList = from o in db.OrderInfo
115                             where o.CustomerID == 2
116                             select o;
117 
118         }
119 
120     }
121 }

 三、第三种codeFirst模式,该模式是指不建立数据模型,并且不建立建立数据库的情况下,通过代码的形式去新建一个数据库。

   1. :创建实体类,并且给实体加上特性标签,并且标注一下实体类之间的关系。

     1.1创建classInfo(班级)实体类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace CodeFirstDemo
 9 {
10    public class ClassInfo
11     {
12        [Key]  //特性标签
13        public int Id { get; set; }
14        [StringLength(32)]   //指定是字符串类型
15        [Required]            //必填项
16        public string ClassName { get; set; }
17        [Required]
18        public DateTime CreateTime { get; set; }
19        //表示1对多,指一个班级对应多个学生
20        public virtual ICollection<StudentInfo> StudentInfo { get; set; }
21     }
22 }

  1.2 :创建学生实体类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace CodeFirstDemo
 9 {
10    public class StudentInfo
11     {
12        [Key]
13        public int Id { get; set; }
14        [StringLength(32)]
15        [Required]
16        public string StuName { get; set; }
17         [Required]
18        public DateTime SubTime { get; set; }
19        public virtual ClassInfo ClassInfo { get; set; }  //表明外键关系,多对1
20     }
21 }

1.3. 引用Entity

  方法1,点击引用,system.data.Entity

  方法2. 新建一个数据模型,之后删掉,此时已经自动引用了entity

1.4 :创建codefirstdbcontext:dbcontext文件

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data.Entity;
 4 using System.Data.Entity.ModelConfiguration.Conventions;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace CodeFirstDemo
10 {
11    public class CodeFirstDbContext:DbContext
12     {
13        public CodeFirstDbContext()
14            : base("name=connStr")  //对应连接数据库字符串的名字
15        {
16 
17        }
18        protected override void OnModelCreating(DbModelBuilder modelBuilder)
19        {
20            //此代码的功能是移除复数的约定  就是指生成的表名后面不加S
21            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
22        }
23         //对应的表
24        public DbSet<ClassInfo> ClassInfo { get; set; }
25        public DbSet<StudentInfo> StudentInfo { get; set; }
26     }
27 }

1.5 :在配置文件构建数据库链接字符串。

1  <configSections>
2     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
3   </configSections>

 

1.6:查询部分数据以及实例创建代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 只查询其中几列数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            //使用HttpContext,只要持续调用,就一直都不会中断 
            EFFristModelEntities db = null;
            if (HttpContext.Current.Items["db"] == null)
            {
                db = new EFFristModelEntities();
                HttpContext.Current.Items["db"] = db;
            }
            else
            {
                db = HttpContext.Current.Items["db"] as EFFristModelEntities;
            }

           var userInfoList = from u in db.UserInfo
                               where u.ID == 343
                               select  new{UName=u.UserName,UPwd=u.UserPass};    //新建一个匿名类查询
            foreach (var userInfo in userInfoList)
            {
                Response.Write(userInfo.UName+":"+userInfo.UPwd);
            }

        }
        /// <summary>
        /// 匿名函数来查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
          //  Func<UserInfo, bool> whereLambda = u => { return u.ID == 343; };
          
            EFFristModelEntities db = new EFFristModelEntities();
            //var userInfoList = db.UserInfo.Where<UserInfo>(u=>u.ID==3);
           
            //select * from UserInfo where id=343
            //升序排序
            //var userInfoList = db.UserInfo.Where<UserInfo>(U => true).OrderBy<UserInfo, int>(u => u.ID);
            //降序排序
         //var userInfoList = db.UserInfo.Where<UserInfo>(U => true).OrderByDescending(u => u.ID);

            int pageIndex = 2;
            int pageSize = 2;
            var userInfoList = (from u in db.UserInfo
                                where u.ID > 0
                                orderby u.RegTime ascending, u.ID descending
                                select u).Skip<UserInfo>((pageIndex - 1) * pageSize).Take<UserInfo>(pageSize);
         
      //   var userInfoList = db.UserInfo.Where<UserInfo>(U => true).OrderByDescending(u => u.UserPass).ThenByDescending<UserInfo, int>(u => u.ID);//Skip:表示跳过多少条记录, Take取多少条记录

      
            foreach (var userInfo in userInfoList)
            {
             
                    Response.Write(userInfo.UserName + "<br/>");
              
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            string str ="ttttt";
          Response.Write (str.MyStr());
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            EFFristModelEntities db = new EFFristModelEntities();
          
            var userInfoList = db.UserInfo.Where<UserInfo>(u => u.ID >0);
        
            int i = 0;
            int count = userInfoList.Count();
            Response.Write(count);

        }
    }
}
查询部分数据以及实例创建代码

以上就是EF创建和操作的详细介绍,欢迎评论和留言

 

org.apache.curator.framework.CuratorFramework的实例源码

org.apache.curator.framework.CuratorFramework的实例源码

项目:dble    文件:ZKUtils.java   
@H_301_8@private static CuratorFramework createConnection() { String url = ZkConfig.getInstance().getZkURL(); CuratorFramework framework = CuratorFrameworkFactory.newClient(url,new ExponentialBackoffRetry(100,6)); // start connection framework.start(); // wait 3 second to establish connect try { framework.blockUntilConnected(3,TimeUnit.SECONDS); if (framework.getZookeeperClient().isConnected()) { LOGGER.info("CuratorFramework createConnection success"); return framework; } } catch (InterruptedException ignored) { LOGGER.info("CuratorFramework createConnection error",ignored); Thread.currentThread().interrupt(); } // fail situation framework.close(); throw new RuntimeException("Failed to connect to zookeeper service : " + url); }
项目:mycat-src-1.6.1-RELEASE    文件:ZKUtils.java   
@H_301_8@private static CuratorFramework createConnection() { String url= ZkConfig.getInstance().getZkURL(); CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(url,6)); // start connection curatorFramework.start(); // wait 3 second to establish connect try { curatorFramework.blockUntilConnected(3,TimeUnit.SECONDS); if (curatorFramework.getZookeeperClient().isConnected()) { return curatorFramework; } } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } // fail situation curatorFramework.close(); throw new RuntimeException("Failed to connect to zookeeper service : " + url); }
项目:zoomap    文件:ZooMap.java   
@H_301_8@private ZooMap(Builder builder) { this.connectionString = builder.connectionString; ConnectStringParser connectStringParser = new ConnectStringParser(connectionString); if(connectStringParser.getChrootPath() != null) { final String connectionStringForChrootCreation = connectStringParser.getServerAddresses().stream().map(InetSocketAddress::toString).collect(Collectors.joining(",")); try(final CuratorFramework clientForChrootCreation = newCuratorFrameworkClient(builder,connectionStringForChrootCreation)) { startAndBlock(clientForChrootCreation); tryIt(() -> clientForChrootCreation.createContainers(connectStringParser.getChrootPath())); } } client = newCuratorFrameworkClient(builder,connectionString); this.root = builder.root; startAndBlock(client); if(!root.isEmpty()) { tryIt(() -> client.createContainers(root)); } }
项目:fastmq    文件:ZkOffsetStorageImpltest.java   
@H_301_8@@Before public void setUp() throws Exception { Configurator .initialize("FastMQ",Thread.currentThread().getContextClassLoader(),"log4j2.xml"); Log log = new Log(); LogSegment logSegment = new LogSegment(); logSegment.setLedgerId(ledgerId); logSegment.setTimestamp(System.currentTimeMillis()); log.setSegments(Collections.singletonList(logSegment)); when(logInfoStorage.getLogInfo(any())).thenReturn(log); CuratorFramework curatorFramework = CuratorFrameworkFactory .newClient("127.0.0.1:2181",new ExponentialBackoffRetry(1000,3)); curatorFramework.start(); asyncCuratorFramework = AsyncCuratorFramework.wrap(curatorFramework); offsetStorage = new ZkOffsetStorageImpl(logInfoStorage,asyncCuratorFramework); }
项目:QDrill    文件:ZkAbstractStore.java   
@H_301_8@public ZkAbstractStore(CuratorFramework framework,PStoreConfig<V> config) throws IOException { this.parent = "/" + config.getName(); this.prefix = parent + "/"; this.framework = framework; this.config = config; // make sure the parent node exists. try { if (framework.checkExists().forPath(parent) == null) { framework.create().withMode(CreateMode.PERSISTENT).forPath(parent); } this.childrenCache = new PathChildrenCache(framework,parent,true); this.childrenCache.start(StartMode.BUILD_INITIAL_CACHE); } catch (Exception e) { throw new RuntimeException("Failure while accessing Zookeeper for PStore: " + e.getMessage(),e); } }
项目:dble    文件:ProxyMetaManager.java   
@H_301_8@public void notifyClusterDDL(String schema,String table,String sql,DDLInfo.DDLStatus ddlStatus,boolean neednotifyOther) throws Exception { CuratorFramework zkConn = ZKUtils.getConnection(); DDLInfo ddlInfo = new DDLInfo(schema,sql,ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID),ddlStatus); String nodeName = StringUtil.getFullName(schema,table); String nodePath = ZKPaths.makePath(KVPathUtil.getDDLPath(),nodeName); if (zkConn.checkExists().forPath(nodePath) == null) { zkConn.create().forPath(nodePath,ddlInfo.toString().getBytes(StandardCharsets.UTF_8)); } else { String instancePath = ZKPaths.makePath(nodePath,KVPathUtil.DDL_INSTANCE); String thisNode = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID); ZKUtils.createTempNode(instancePath,thisNode); if (neednotifyOther) { //this node is ddl sender zkConn.setData().forPath(nodePath,ddlInfo.toString().getBytes(StandardCharsets.UTF_8)); while (true) { List<String> preparedList = zkConn.getChildren().forPath(instancePath); List<String> onlineList = zkConn.getChildren().forPath(KVPathUtil.getonlinePath()); if (preparedList.size() >= onlineList.size()) { zkConn.delete().deletingChildrenIfNeeded().forPath(nodePath); break; } LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); } } } }
项目:sNowflake    文件:TestSeqBase.java   
@H_301_8@public ZkRangeStore getZkRangeStore(int clientIndex) { String lockPath = "/sNowflake/locks"; String storePath = "/sNowflake/idstore"; CuratorFramework curatorFramework = ZkUtils.create("127.0.0.1:2181",1000,10000); curatorFramework.start(); for (String client : clients) { try { curatorFramework.setData().forPath(ZKPaths.makePath(storePath,client),"0".getBytes()); } catch (Exception e) { if (e instanceof KeeperException.NoNodeException) { try { curatorFramework.create().creatingParentsIfNeeded().forPath(storePath,"0".getBytes()); } catch (Exception e1) { e1.printstacktrace(); } } } } return new ZkRangeStore(clients.get(clientIndex),curatorFramework,lockPath,storePath,1,TimeUnit.SECONDS,10); }
项目:flume-release-1.7.0    文件:StaticZooKeeperConfigurationProvider.java   
@H_301_8@@Override protected FlumeConfiguration getFlumeConfiguration() { try { CuratorFramework cf = createClient(); cf.start(); try { byte[] data = cf.getData().forPath(basePath + "/" + getAgentName()); return configFromBytes(data); } finally { cf.close(); } } catch (Exception e) { LOGGER.error("Error getting configuration info from Zookeeper",e); throw new FlumeException(e); } }
项目:trellis-rosid-file    文件:FileResourceService.java   
@H_301_8@/** * Create a File-based repository service * @param partitionData the partition data configuration * @param partitionUrls the partition URL configuration * @param curator the curator framework * @param producer the kafka producer * @param notifications the notification service * @param idsupplier an identifier supplier for new resources * @param async generate cached resources asynchronously if true,synchonously if false * @throws IOException if the directory is not writable */ public FileResourceService(final Map<String,String> partitionData,final Map<String,String> partitionUrls,final CuratorFramework curator,final Producer<String,String> producer,final EventService notifications,final supplier<String> idsupplier,final Boolean async) throws IOException { super(partitionUrls,producer,curator,notifications,idsupplier,async); requireNonNull(partitionData,"partition data configuration may not be null!"); RESERVED_PARTITION_NAMES.stream().filter(partitionData::containsKey).findAny().ifPresent(name -> { throw new IllegalArgumentException("Invalid partition name: " + name); }); this.partitionData = partitionData; init(); }
项目:redirector    文件:AbstractCommonBeans.java   
@H_301_8@@Bean public CuratorFramework curatorFramework() { ZKConfig config = config(); if (config.useZooKeeperWaitTimePolicy()) { return new RedirectorCuratorFramework(config); } CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(config.getZooKeeperConnection()) .connectionTimeoutMs(config.getZooKeeperConnectionTimeout()) .sessionTimeoutMs(config.getZooKeeperSessionTimeout()) .retryPolicy(new RetryNTimes(config.getZooKeeperRetryAttempts(),config.getZooKeeperRetryInterval())) .compressionProvider(new GzipCompressionProvider()); return builder.build(); }
项目:jigsaw-payment    文件:HelloServerConfig.java   
@H_301_8@@Bean(name = "curator-framework") public CuratorFramework curatorFramework() { return CuratorFrameworkFactory .builder() .connectString( env.getProperty("rpc.server.zookeeper.connect.string")) .sessionTimeoutMs( Integer.parseInt(env.getProperty( "rpc.server.zookeeper.session.timeout.ms","10000"))) .connectionTimeoutMs( Integer.parseInt(env.getProperty( "rpc.server.zookeeper.connection.timeout.ms","10000"))).retryPolicy(this.retryPolicy()) .aclProvider(this.aclProvider()).authorization(this.authInfo()) .build(); }
项目:dble    文件:ViewChildListener.java   
@H_301_8@@Override public void childEvent(CuratorFramework client,PathChildrenCacheEvent event) throws Exception { ChildData childData = event.getData(); switch (event.getType()) { case CHILD_ADDED: createOrUpdateViewMeta(childData,false); break; case CHILD_UPDATED: createOrUpdateViewMeta(childData,true); break; case CHILD_REMOVED: deleteNode(childData); break; default: break; } }
项目:GoPush    文件:ZkUtils.java   
@H_301_8@/** * 设置子节点更改监听 * * @param path * @throws Exception */ public boolean listenerPathChildrenCache(String path,BiConsumer<CuratorFramework,PathChildrenCacheEvent> biConsumer) { if (!ObjectUtils.allNotNull(zkClient,path,biConsumer)) { return Boolean.FALSE; } try { Stat stat = exists(path); if (stat != null) { PathChildrenCache watcher = new PathChildrenCache(zkClient,true); watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); //该模式下 watcher在重连的时候会自动 rebuild 否则需要重新rebuild watcher.getListenable().addListener(biConsumer::accept,pool); if (!pathChildrenCaches.contains(watcher)) { pathChildrenCaches.add(watcher); } // else{ // watcher.rebuild(); // } return Boolean.TRUE; } } catch (Exception e) { log.error("listen path children cache fail! path:{},error:{}",e); } return Boolean.FALSE; }
项目:mycat-src-1.6.1-RELEASE    文件:RulesxmlTozkLoader.java   
@H_301_8@public RulesxmlTozkLoader(ZookeeperProcessListen zookeeperListen,CuratorFramework curator,XmlProcessBase xmlParseBase) { this.setCurator(curator); // 获得当前集群的名称 String schemaPath = zookeeperListen.getBasePath(); schemaPath = schemaPath + ZookeeperPath.ZK_SEParaTOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_RULE.getKey(); currZkPath = schemaPath; // 将当前自己注册为事件接收对象 zookeeperListen.addListen(schemaPath,this); // 生成xml与类的转换信息 parseRulesXMl = new RuleParseXmlImpl(xmlParseBase); }
项目:dble    文件:DbleServer.java   
@H_301_8@private void initZkDnindex() { //upload the dnindex data to zk try { if (dnIndexLock.acquire(30,TimeUnit.SECONDS)) { try { File file = new File(SystemConfig.getHomePath(),"conf" + File.separator + "dnindex.properties"); String path = KVPathUtil.getDnIndexNode(); CuratorFramework zk = ZKUtils.getConnection(); if (zk.checkExists().forPath(path) == null) { zk.create().creatingParentsIfNeeded().forPath(path,Files.toByteArray(file)); } } finally { dnIndexLock.release(); } } } catch (Exception e) { throw new RuntimeException(e); } }
项目:DBus    文件:EventContainer.java   
@H_301_8@/** * 在拉完全量后将此schema的kafka consumer的offset设置为最新 * @param dbSchema */ /*public void setKafkaOffsetToLargest(String targetTopic){ if(targetTopic==null) return; TopicPartition partition0 = new TopicPartition(targetTopic,0); KafkaConsumerContainer.getInstances().getConsumer(targetTopic).seekToEnd(Arrays.asList(partition0)); }*/ protected <T> T deserialize(String path,Class<T> clazz) throws Exception { T packet = null; CuratorFramework curator = CuratorContainer.getInstance().getCurator(); if (curator.getState() == CuratorFrameworkState.STOPPED) { LOG.info("[EventContainer] CuratorFrameworkState:{}",CuratorFrameworkState.STOPPED.name()); } else { byte[] bytes = curator.getData().forPath(path); if (bytes != null && bytes.length != 0) { packet = JsonUtil.fromJson(new String(bytes,Charset.forName("UTF-8")),clazz); } } return packet; }
项目:stroom-stats    文件:ServicediscoveryManager.java   
@H_301_8@@Inject public ServicediscoveryManager(final @ServicediscoveryCuratorFramework CuratorFramework curatorFramework) throws Exception { LOGGER.info("ServicediscoveryManager starting..."); this.curatorFrameworkRef.set(curatorFramework); // // First register this service // servicediscovery = ServicediscoveryBuilder // .builder(String.class) // .client(curatorFramework) // .basePath("/") // .thisinstance(getThisServiceInstance(config)) // .build(); // servicediscovery.start(); // Then register services this service depends on // Arrays.stream(ExternalService.values()).forEach(externalService -> // serviceProviders.put(externalService,createProvider(externalService.get()))); }
项目:stroom-stats    文件:ServicediscoveryCuratorFrameworkProvider.java   
@H_301_8@@Override public CuratorFramework get() { String quorum = zookeeperConfig.getQuorum(); String servicediscoveryPath = zookeeperConfig.getServicediscoveryPath(); String connectionString = quorum + (servicediscoveryPath == null ? "" : servicediscoveryPath); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3); LOGGER.info("Initiating Curator connection to Zookeeper using: [{}]",connectionString); // Use chroot so all subsequent paths are below /stroom-services to avoid conflicts with hbase/zookeeper/kafka etc. CuratorFramework client = CuratorFrameworkFactory.newClient(connectionString,retryPolicy); client.start(); try { //Ensure the chrooted path for stroom-services exists Stat stat = client.checkExists().forPath("/"); if (stat == null) { LOGGER.info("Creating chroot-ed root node inside " + servicediscoveryPath); client.create().forPath("/"); } } catch (Exception e) { throw new RuntimeException("Error connecting to zookeeper using connection String: " + connectionString,e); } return client; }
项目:redirector    文件:RedirectorCuratorFramework.java   
@H_301_8@@Override public void stateChanged(CuratorFramework client,ConnectionState newState) { if (newState == ConnectionState.CONNECTED) { isConnected.set(true); if (!isFirstConnection.get()) { for (ConnectionStateListener listener : listenerStateProxy.getListeners()) { listener.stateChanged(client,ConnectionState.RECONNECTED); } } return; } if (newState == ConnectionState.LOST) { isConnected.set(false); isFirstConnection.set(false); retryConnection(); } }
项目:mycat-src-1.6.1-RELEASE    文件:RuleDataPathChildrenCacheListener.java   
@H_301_8@@Override public void childEvent(CuratorFramework client,PathChildrenCacheEvent event) throws Exception { ChildData data = event.getData(); switch (event.getType()) { case CHILD_ADDED: add(data.getPath().substring(data.getPath().lastIndexOf("/")+1),event.getData().getData()) ; break; case CHILD_REMOVED: delete(data.getPath().substring(data.getPath().lastIndexOf("/")+1),event.getData().getData()); ; break; case CHILD_UPDATED: add(data.getPath().substring(data.getPath().lastIndexOf("/")+1),event.getData().getData()) ; break; default: break; } }
项目:mycat-src-1.6.1-RELEASE    文件:EcacheszkToxmlLoader.java   
@H_301_8@public EcacheszkToxmlLoader(ZookeeperProcessListen zookeeperListen,XmlProcessBase xmlParseBase) { this.setCurator(curator); this.zookeeperListen = zookeeperListen; // 获得当前集群的名称 String schemaPath = zookeeperListen.getBasePath(); schemaPath = schemaPath + ZookeeperPath.ZK_SEParaTOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_CACHE.getKey(); currZkPath = schemaPath; // 将当前自己注册为事件接收对象 this.zookeeperListen.addListen(schemaPath,this); // 生成xml与类的转换信息 parseEcacheXMl = new EhcacheParseXmlImpl(xmlParseBase); }
项目:mycat-src-1.6.1-RELEASE    文件:ServerzkToxmlLoader.java   
@H_301_8@public ServerzkToxmlLoader(ZookeeperProcessListen zookeeperListen,XmlProcessBase xmlParseBase) { this.setCurator(curator); this.zookeeperListen = zookeeperListen; // 获得当前集群的名称 String serverPath = zookeeperListen.getBasePath(); serverPath = serverPath + ZookeeperPath.ZK_SEParaTOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_SERVER.getKey(); currZkPath = serverPath; // 将当前自己注册为事件接收对象 this.zookeeperListen.addListen(serverPath,this); // 生成xml与类的转换信息 parseServerXMl = new ServerParseXmlImpl(xmlParseBase); }
项目:mycat-src-1.6.1-RELEASE    文件:XmltoZkMain.java   
@H_301_8@private static CuratorFramework buildConnection(String url) { CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(url,TimeUnit.SECONDS); if (curatorFramework.getZookeeperClient().isConnected()) { return curatorFramework.usingNamespace(""); } } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } // fail situation curatorFramework.close(); throw new RuntimeException("Failed to connect to zookeeper service : " + url); }
项目:mycat-src-1.6.1-RELEASE    文件:EcachesxmlTozkLoader.java   
@H_301_8@public EcachesxmlTozkLoader(ZookeeperProcessListen zookeeperListen,XmlProcessBase xmlParseBase) { this.setCurator(curator); // 获得当前集群的名称 String schemaPath = zookeeperListen.getBasePath(); schemaPath = schemaPath + ZookeeperPath.ZK_SEParaTOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_CACHE.getKey(); currZkPath = schemaPath; // 将当前自己注册为事件接收对象 zookeeperListen.addListen(schemaPath,this); // 生成xml与类的转换信息 parseEcacheXMl = new EhcacheParseXmlImpl(xmlParseBase); }
项目:mycat-src-1.6.1-RELEASE    文件:ServerxmlTozkLoader.java   
@H_301_8@public ServerxmlTozkLoader(ZookeeperProcessListen zookeeperListen,XmlProcessBase xmlParseBase) { this.setCurator(curator); // 获得当前集群的名称 String schemaPath = zookeeperListen.getBasePath(); schemaPath = schemaPath + ZookeeperPath.ZK_SEParaTOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_SERVER.getKey(); currZkPath = schemaPath; // 将当前自己注册为事件接收对象 zookeeperListen.addListen(schemaPath,this); // 生成xml与类的转换信息 parseServerXMl = new ServerParseXmlImpl(xmlParseBase); }
项目:mycat-src-1.6.1-RELEASE    文件:SchemasxmlTozkLoader.java   
@H_301_8@public SchemasxmlTozkLoader(ZookeeperProcessListen zookeeperListen,XmlProcessBase xmlParseBase) { this.setCurator(curator); // 获得当前集群的名称 String schemaPath = zookeeperListen.getBasePath(); schemaPath = schemaPath + ZookeeperPath.ZK_SEParaTOR.getKey() + ZookeeperPath.FOW_ZK_PATH_SCHEMA.getKey(); currZkPath = schemaPath; // 将当前自己注册为事件接收对象 zookeeperListen.addListen(schemaPath,this); // 生成xml与类的转换信息 this.parseSchemaXmlService = new SchemasParseXmlImpl(xmlParseBase); }
项目:light-tram-4j    文件:CdcServerStartupHookProvider.java   
@H_301_8@CuratorFramework makeStartedCuratorClient(String connectionString) { RetryPolicy retryPolicy = new ExponentialBackoffRetry(2000,6,2000); CuratorFramework client = CuratorFrameworkFactory. builder().connectString(connectionString) .retryPolicy(retryPolicy) .build(); client.start(); return client; }
项目:fastmq    文件:LogManagerFactoryImpl.java   
@H_301_8@public LogManagerFactoryImpl(ClientConfiguration clientConfiguration,BookKeeperConfig config) throws Exception { bookKeeperConfig = config; checkNotNull(clientConfiguration); String servers = clientConfiguration.getZkServers(); checkNotNull(servers); final CountDownLatch countDownLatch = new CountDownLatch(1); zooKeeper = new ZooKeeper(servers,clientConfiguration.getZkTimeout(),event -> { if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { logger.info("Connected to zookeeper,connectString = {}",servers); countDownLatch.countDown(); } else { logger.error("Failed to connect zookeeper,servers); } }); if (!countDownLatch.await(clientConfiguration.getZkTimeout(),TimeUnit.MILLISECONDS) || zooKeeper.getState() != ZooKeeper.States.CONNECTED) { throw new LedgerStorageException( "Error connecting to zookeeper server,connectString = " + servers + "."); } this.bookKeeper = new BookKeeper(clientConfiguration,zooKeeper); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3); CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(servers,retryPolicy); curatorFramework.start(); asyncCuratorFramework = AsyncCuratorFramework.wrap(curatorFramework); logInfoStorage = new LogInfoStorageImpl(asyncCuratorFramework); offsetStorage = new ZkOffsetStorageImpl(logInfoStorage,asyncCuratorFramework); }
项目:zoomap    文件:ZooMap.java   
@H_301_8@private static CuratorFramework newCuratorFrameworkClient(Builder builder,String connectionString) { return CuratorFrameworkFactory.builder() .connectString(connectionString) .retryPolicy(builder.retryPolicy) .connectionTimeoutMs((int) builder.duration.toMillis()) .build(); }
项目:Equella    文件:ClusterMessagingServiceImpl.java   
@H_301_8@@Override public void childEvent(CuratorFramework client,PathChildrenCacheEvent event) throws Exception { Type type = event.getType(); if( type.equals(Type.CHILD_ADDED) || type.equals(Type.CHILD_UPDATED) || type.equals(Type.CHILD_REMOVED) ) { String remoteId = ZKPaths.getNodeFromPath(event.getData().getPath()); String[] clientInfo = new String(event.getData().getData()).split(":"); if( !isThisNode(remoteId) && !hasSameInfo(clientInfo) ) { if( type.equals(Type.CHILD_ADDED) ) { senders.get(remoteId); addReceiver(remoteId,clientInfo); } else if( type.equals(Type.CHILD_UPDATED) ) { senders.get(remoteId); removeReceiver(remoteId); addReceiver(remoteId,clientInfo); } else { removeReceiver(remoteId); } } } }
项目:trellis-rosid    文件:TrellisUtils.java   
@H_301_8@public static CuratorFramework getCuratorClient(final TrellisConfiguration config) { final CuratorFramework curator = newClient(config.getZookeeper().getEnsembleServers(),new BoundedExponentialBackoffRetry(config.getZookeeper().getRetryMs(),config.getZookeeper().getRetryMaxms(),config.getZookeeper().getRetryMax())); curator.start(); return curator; }
项目:redant    文件:DefaultServicediscovery.java   
@H_301_8@@Override public void childEvent(CuratorFramework client,PathChildrenCacheEvent event) throws Exception { ChildData data = event.getData(); if(data==null || data.getData()==null){ return; } SlaveNode slaveNode = SlaveNode.parse(JSON.parSEObject(data.getData(),JSONObject.class)); if(slaveNode==null){ LOGGER.error("get a null slaveNode with eventType={},path={},data={}",event.getType(),data.getPath(),data.getData()); }else { switch (event.getType()) { case CHILD_ADDED: slaveNodeMap.put(slaveNode.getId(),slaveNode); LOGGER.info("CHILD_ADDED with path={},data={},current slaveNode size={}",new String(data.getData(),CharsetUtil.UTF_8),slaveNodeMap.size()); break; case CHILD_REMOVED: slaveNodeMap.remove(slaveNode.getId()); LOGGER.info("CHILD_REMOVED with path={},slaveNodeMap.size()); break; case CHILD_UPDATED: slaveNodeMap.replace(slaveNode.getId(),slaveNode); LOGGER.info("CHILD_UPDATED with path={},slaveNodeMap.size()); break; default: break; } } }
项目:leaf-sNowflake    文件:Zookeeper.java   
@H_301_8@public void deletereRcursive(CuratorFramework zk,String path) throws Exception { String npath = PathUtils.normalize_path(path); if (existsNode(zk,npath,false)) { zk.delete().guaranteed().deletingChildrenIfNeeded().forPath(npath); } }
项目:monica    文件:RouteHandler.java   
@H_301_8@private void rulesInit() { final CuratorFramework zkClient = (CuratorFramework) RegistryContext.clientCache.get("curatorClient"); try { if (null != zkClient.checkExists().forPath(RULES_PATH)) { List<String> childList = zkClient.getChildren().forPath(RULES_PATH); for (String rule : childList) { StringToObjectParser stringParser = new StringToObjectParser(); rulesList.add(stringParser.parseRuleStringToRule(URLDecoder.decode(rule,"UTF-8"))); } } filterRulesForConsumer(); } catch (Exception e) { e.printstacktrace(); } }
项目:redirector    文件:RedirectorCuratorFramework.java   
@H_301_8@private synchronized CuratorFramework buildCuratorFramework(final ZKConfig config) { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(config.getZooKeeperConnection()) .connectionTimeoutMs(config.getZooKeeperConnectionTimeout()) .sessionTimeoutMs(config.getZooKeeperSessionTimeout()) .retryPolicy(new RetryNTimes(config.getZooKeeperRetryAttempts(),config.getZooKeeperRetryInterval())) .compressionProvider(new GzipCompressionProvider()); CuratorFramework framework = builder.build(); listenerStateProxy.updateCurator(framework); listenerProxy.updateCurator(framework); return framework; }
项目:dble    文件:RuleszkToxmlLoader.java   
@H_301_8@public RuleszkToxmlLoader(ZookeeperProcessListen zookeeperListen,XmlProcessBase xmlParseBase,ConfigStatusListener confListener) { this.setCurator(curator); currZkPath = KVPathUtil.getConfRulePath(); zookeeperListen.addToInit(this); parseRulesXMl = new RuleParseXmlImpl(xmlParseBase); confListener.addChild(this); }
项目:idworker    文件:ZookeeperConnectionStateListener.java   
@H_301_8@@Override public void stateChanged(CuratorFramework client,ConnectionState newState) { switch (newState) { case LOST: logger.warn("zookeeper connection session lost,try to register new worker id."); doReconnecting(); break; case SUSPENDED: logger.warn("zookeeper suspended,try to register new worker id."); doReconnecting(); break; default: break; } }
项目:redirector    文件:ZookeeperConnector.java   
@H_301_8@private CuratorFramework obtainClient() { lock.lock(); try { if (client == null) { connect(); } return client; } finally { lock.unlock(); } }
项目:sNowflake    文件:SNowflakeServer.java   
@H_301_8@@Override public void stateChanged(CuratorFramework curatorFramework,ConnectionState connectionState) { if (curatorFramework.getConnectionStateErrorPolicy().isErrorState(connectionState)) { reset(); throw new CancelleadershipException(); } }
项目:trellis-rosid    文件:NamespacesTest.java   
@H_301_8@@Test public void testNamespaces() throws Exception { final URL res = Namespaces.class.getResource(nsDoc); final CuratorFramework zk = newClient(curator.getConnectString(),new RetryNTimes(10,1000)); zk.start(); final TreeCache cache = new TreeCache(zk,ZNODE_NAMESPACES); cache.start(); final NamespaceService svc1 = new Namespaces(zk,cache,res.getPath() + randomFilename()); assertEquals(0,svc1.getNamespaces().size()); final NamespaceService svc2 = new Namespaces(zk,res.getPath()); assertEquals(2,svc2.getNamespaces().size()); assertEquals(LDP.URI,svc2.getNamespace("ldp").get()); assertEquals("ldp",svc2.getPrefix(LDP.URI).get()); assertFalse(svc2.getNamespace("jsonld").isPresent()); assertFalse(svc2.getPrefix(JSONLD.URI).isPresent()); assertTrue(svc2.setPrefix("jsonld",JSONLD.URI)); assertEquals(3,svc2.getNamespaces().size()); assertEquals(JSONLD.URI,svc2.getNamespace("jsonld").get()); assertEquals("jsonld",svc2.getPrefix(JSONLD.URI).get()); final Namespaces svc3 = new Namespaces(zk,cache); await().atMost(5,SECONDS).until(() -> 3 == svc3.getNamespaces().size()); assertEquals(JSONLD.URI,svc3.getNamespace("jsonld").get()); assertFalse(svc3.setPrefix("jsonld",JSONLD.URI)); }

org.apache.curator.framework.imps.CuratorFrameworkState的实例源码

org.apache.curator.framework.imps.CuratorFrameworkState的实例源码

项目:DBus    文件:EventContainer.java   
/**
 * 在拉完全量后将此schema的kafka consumer的offset设置为最新
 * @param dbSchema
 */
/*public void setKafkaOffsetToLargest(String targetTopic){
    if(targetTopic==null)
        return;
    TopicPartition partition0 = new TopicPartition(targetTopic,0);
    KafkaConsumerContainer.getInstances().getConsumer(targetTopic).seekToEnd(Arrays.asList(partition0));
}*/

protected <T> T deserialize(String path,Class<T> clazz) throws Exception {
    T packet = null;
    CuratorFramework curator = CuratorContainer.getInstance().getCurator();
    if (curator.getState() == CuratorFrameworkState.STOPPED) {
        LOG.info("[EventContainer] CuratorFrameworkState:{}",CuratorFrameworkState.STOPPED.name());
    } else {
        byte[] bytes = curator.getData().forPath(path);
        if (bytes != null && bytes.length != 0) {
            packet = JsonUtil.fromJson(new String(bytes,Charset.forName("UTF-8")),clazz);
        }
    }
    return packet;
}
项目:asura    文件:ConfigPublisher.java   
/**
 * 初始化
 *
 * @author zhangshaobin
 * @created 2013-6-26 上午10:55:30
 */
private void init() {
    applicationName = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.CONfig_APPLICATION_NAME_KEY,null).get();
    String zkConfigEnsemble = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.ZK_ENSEMABLE_KEY,null).get();
    Integer zkConfigSessionTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_SESSION_TIMEOUT_KEY,15000).get();
    Integer zkConfigConnTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_CONN_TIMEOUT_KEY,5000).get();

    if (Check.NuNStr(zkConfigEnsemble)) {
        logger.warn("ZooKeeper configuration running in file mode,zk is not enabled since not configured");
        return;
    }

    try {
        client = createAndStartZKClient(zkConfigEnsemble,zkConfigSessionTimeout,zkConfigConnTimeout);

        if (client.getState() != CuratorFrameworkState.STARTED) {
            throw new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started.");
        }
    } catch (Exception e) {
        e.printstacktrace();
        logger.error("连接配置中心服务器超时,时间5000毫秒。",e.getCause());
        System.exit(1);
    }
    System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date()) + applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
    logger.info(applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
}
项目:albedo-thrift    文件:ThriftServerAddressRegisterZookeeper.java   
@Override
public void register(String service,String version,String address) {
    if(zkClient.getState() == CuratorFrameworkState.LATENT){
        zkClient.start();
    }
    if (version == null || version == ""){
        version ="1.0.0";
    }
    //创建临时节点
    try {
        zkClient.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath("/"+service+"/"+version+"/"+address);
    } catch (Exception e) {
        logger.error("register service address to zookeeper exception:{}",e);
        throw new ThriftException("register service address to zookeeper exception:{}",e);
    }
}
项目:albedo-thrift    文件:ZookeeperServiceRegister.java   
@Override
public void register(String service,String address) {
    if(curatorFramework.getState() == CuratorFrameworkState.LATENT){
        curatorFramework.start();
    }
    if (version == null || version == ""){
        version = ThriftConstant.DEFAULT_VERSION;
    }

    //创建临时节点
    try {
        String path = "/"+service+"/"+version+"/"+address;
        logger.info("register: {}",path);
        curatorFramework.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(path);
    } catch (Exception e) {
        logger.error("register service address to zookeeper exception:{}",e);
    }
}
项目:niubi-job    文件:MasterSlaveNode.java   
@Override
public void relinquishleadership() {
    try {
        if (nodeCache != null) {
            nodeCache.close();
        }
        LoggerHelper.info("node cache has been closed.");
    } catch (Throwable e) {
        LoggerHelper.warn("node cache close Failed.",e);
    }
    if (client.getState() == CuratorFrameworkState.STARTED) {
        MasterSlaveNodeData.Data nodeData = new MasterSlaveNodeData.Data(getNodeIp());
        releaseJobs(nodePath,nodeData);
        nodeData.setNodeState("Slave");
        masterSlaveApiFactory.nodeApi().updateNode(nodePath,nodeData);
    }
    LoggerHelper.info("clear node successfully.");
}
项目:niubi-job    文件:StandbyNode.java   
@Override
public void relinquishleadership() {
    try {
        if (jobcache != null) {
            jobcache.close();
        }
        LoggerHelper.info("job cache has been closed.");
    } catch (Throwable e) {
        LoggerHelper.warn("job cache close Failed.",e);
    }
    LoggerHelper.info("begin stop scheduler manager.");
    schedulerManager.shutdown();
    if (client.getState() == CuratorFrameworkState.STARTED) {
        StandbyNodeData.Data data = new StandbyNodeData.Data(getNodeIp());
        standbyApiFactory.nodeApi().updateNode(nodePath,data);
        LoggerHelper.info(getNodeIp() + " has been shutdown. [" + data + "]");
    }
    LoggerHelper.info("clear node successfully.");
}
项目:Mastering-Mesos    文件:StateManager.java   
public void save(SingularityHostState hostState) throws InterruptedException {
  final String path = ZKPaths.makePath(ROOT_PATH,hostState.getHostname());
  final byte[] data = hostStateTranscoder.toBytes(hostState);

  if (curator.getState() == CuratorFrameworkState.STARTED) {
    try {
      if (exists(path)) {
        curator.setData().forPath(path,data);
      } else {
        curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path,data);
      }
    } catch (Throwable t) {
      throw Throwables.propagate(t);
    }
  }
}
项目:bigstreams    文件:ZConnectionIntegrationTest.java   
/**
 * Test the timeout exception
 * 
 * @throws IOException
 * @throws InterruptedException
 */
@Test
public void testConnect() throws IOException,InterruptedException {

    // we expect a ConnectException to be thrown
    final ZConnection conn = new ZConnection("localhost:" + server.getPort(),10000L);

    try {
        CuratorFramework zk = conn.get();

        assertTrue(zk.getState().compareto(CuratorFrameworkState.STARTED) == 0);

    } finally {
        conn.close();
    }

}
项目:java-restify    文件:ZookeeperServicediscovery.java   
private Servicediscovery<ZookeeperInstance> buildServicediscoveryWith(ZookeeperConfiguration configuration,CuratorFramework curator,InstanceSerializer<ZookeeperInstance> serializer) {

    try {
        if (!CuratorFrameworkState.STARTED.equals(curator.getState())) {
            curator.start();
        }

        Servicediscovery<ZookeeperInstance> servicediscovery = ServicediscoveryBuilder.builder(ZookeeperInstance.class)
                .client(curator)
                    .basePath(configuration.root())
                    .serializer(serializer)
                        .build();

        servicediscovery.start();

        return servicediscovery;
    } catch (Exception e) {
        throw new ZookeeperServicediscoveryException("Error on create Zookeeper Servicediscovery",e);
    }
}
项目:Hvalspik    文件:CuratorWait.java   
@Override
public WaitResult wait(DockerFacade dockerClient,Container container) {
  return new PortWait().wait(ZOOKEEPER_PORT,dockerClient,container,(ipAddress,externalPort) -> {
    String zookeeperConnectionString = String.format("%s:%s",ipAddress,externalPort);
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
    CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString,retryPolicy);
    client.start();
    try {
      client.blockUntilConnected();
      CuratorFrameworkState status = client.getState();
      if (!status.equals(CuratorFrameworkState.STARTED)) {
        return WaitResult.failure("Status [%s] does not match expected [STARTED]",status);
      }
      return WaitResult.success();
    } catch (InterruptedException e) {
      throw new RuntimeException("Could not connect to Zookeeper",e);
    } finally {
      client.close();
    }

  });
}
项目:distributed-phtree    文件:ZKClusterService.java   
private synchronized ZMapping readCurrentMapping(Stat stat) {
    ZMapping zMap = null;
    try {
        if (client.getState().equals(CuratorFrameworkState.STOPPED)) {
            LOG.warn("Attempting to read state on stopped client.");
            return null;
        }
        byte[] data = client.getData().storingStatIn(stat).usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent watchedEvent) throws Exception {
                ZMapping newMapping = readCurrentMapping();
                if (newMapping == null && mapping != null) {
                    LOG.warn("An attempt was made to overwrite current mapping with a null one.");
                } else {
                    mapping = newMapping;
                }
                LOG.debug("Host {} just updated its mapping to version {}",hostPort,(mapping != null) ? mapping.getVersion() : -1);
            }
        }).forPath(MAPPING_PATH);
        zMap = ZMapping.deserialize(data);
    } catch (Exception e) {
        LOG.error("Error reading current mapping: ",e);
    }
    return zMap;
}
项目:spring-cloud-zookeeper    文件:ZookeeperHealthindicator.java   
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    try {
        if (this.curator.getState() != CuratorFrameworkState.STARTED) {
            builder.down().withDetail("error","Client not started");
        }
        else if (this.curator.checkExists().forPath("/") == null) {
            builder.down().withDetail("error","Root for namespace does not exist");
        }
        else {
            builder.up();
        }
        builder.withDetail("connectionString",this.curator.getZookeeperClient().getCurrentConnectionString())
                .withDetail("state",this.curator.getState());
    }
    catch (Exception e) {
        builder.down(e);
    }
}
项目:Decision    文件:ZKUtils.java   
private ZKUtils(String zookeeperCluster,String groupId) throws Exception {

        this.groupId = groupId;

        // ZOOKEPER CONNECTION
        client = CuratorFrameworkFactory.newClient(zookeeperCluster,25 * 1000,10 * 1000,new ExponentialBackoffRetry(
                1000,3));
        client.start();
        client.getZookeeperClient().blockUntilConnectedOrTimedOut();

        if (client.getState().compareto(CuratorFrameworkState.STARTED) != 0) {
            throw new Exception("Connection to Zookeeper timed out after seconds");
        } else {
            backgroundZookeeperCleanerTasks = Executors.newFixedThreadPool(1);
            backgroundZookeeperCleanerTasks.submit(new ZookeeperBackgroundCleaner(client,groupId));
        }


    }
项目:disco-java    文件:discoServiceTest.java   
@SuppressWarnings("unchecked")
@Test
public void testStart() throws Exception {
    CuratorFramework framework = mockFramework();
    ExistsBuilder ceBuilder = mock(ExistsBuilder.class);
    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(framework.checkExists()).thenReturn(ceBuilder);
    when(ceBuilder.forPath("/services/myservice/nodes")).thenReturn(mock(Stat.class));
    when(framework.create()).thenReturn(createBuilder);
    when(framework.getState()).thenReturn(CuratorFrameworkState.STARTED);
    ACLBackgroundpathAndBytesable<String> os = mock(ACLBackgroundpathAndBytesable.class);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(os);
    discoService service = new discoService(framework,"myservice");
    byte[] payload = "foo bar baz bingo".getBytes();
    service.start("foo",4321,true,payload);
    verify(os).forPath(eq("/services/myservice/nodes/foo:4321"),eq(payload));
}
项目:disco-java    文件:discoServiceTest.java   
@SuppressWarnings("unchecked")
@Test
public void testDeletesEphemeralNode() throws Exception {
    CuratorFramework framework = mockFramework();
    ExistsBuilder ceBuilder = mock(ExistsBuilder.class);
    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(framework.checkExists()).thenReturn(ceBuilder);
    when(ceBuilder.forPath("/services/myservice/nodes")).thenReturn(mock(Stat.class));
    when(ceBuilder.forPath("/services/myservice/nodes/foo:4321")).thenReturn(mock(Stat.class));
    when(framework.create()).thenReturn(createBuilder);
    when(framework.getState()).thenReturn(CuratorFrameworkState.STARTED);
    DeleteBuilder deleteBuilder = mock(DeleteBuilder.class);
    when(framework.delete()).thenReturn(deleteBuilder);
    ACLBackgroundpathAndBytesable<String> os = mock(ACLBackgroundpathAndBytesable.class);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(os);
    discoService service = new discoService(framework,payload);
    verify(deleteBuilder).forPath("/services/myservice/nodes/foo:4321");
    verify(os).forPath(eq("/services/myservice/nodes/foo:4321"),eq(payload));
}
项目:spring-cloud-cluster    文件:leaderInitiator.java   
/**
 * Start the registration of the {@link #candidate} for leader election.
 */
@Override
public synchronized void start() {
    if (!this.running) {
        if (this.client.getState() != CuratorFrameworkState.STARTED) {
            // we want to do curator start here because it needs to
            // be started before leader selector and it gets a little
            // complicated to control ordering via beans so that
            // curator is fully started.
            this.client.start();
        }
        this.leaderSelector = new leaderSelector(this.client,buildleaderPath(),new leaderListener());
        this.leaderSelector.setId(this.candidate.getId());
        this.leaderSelector.autoRequeue();
        this.leaderSelector.start();

        this.running = true;
    }
}
项目:curator-extensions    文件:ZooKeeperConfigurationTest.java   
@Test
public void testNewManagedCurator() {
    ZooKeeperConfiguration config = parse(ImmutableMap.of("retryPolicy",ImmutableMap.builder()
                    .put("type","untilElapsed")
                    .put("maxelapsedtimeMs",1000)
                    .put("sleepMsBetweenRetries",50)
                    .build()));

    LifecycleEnvironment env = mock(LifecycleEnvironment.class);
    CuratorFramework curator = config.newManagedCurator(env);

    assertNotNull(curator);
    assertEquals(CuratorFrameworkState.LATENT,curator.getState());
    verify(env).manage(any(ManagedCuratorFramework.class));
}
项目:curator-extensions    文件:PersistentEphemeralNode.java   
/**
 * Create the ephemeral node in ZooKeeper.  If the node cannot be created in a timely fashion then an exception will
 * be thrown.
 */
public PersistentEphemeralNode(CuratorFramework curator,String basePath,byte[] data,CreateMode mode) {
    checkNotNull(curator);
    checkArgument(curator.getState() == CuratorFrameworkState.STARTED);
    checkNotNull(basePath);
    checkNotNull(data);
    checkNotNull(mode);
    checkArgument(mode == CreateMode.EPHEMERAL || mode == CreateMode.EPHEMERAL_SEQUENTIAL);

    // Todo: Share this executor across multiple persistent ephemeral nodes in a way that guarantees that it is a
    // Todo: single thread executor.
    _executor = Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY);
    _async = new Async(_executor,new Sync(curator,basePath,data,mode));

    CountDownLatch latch = new CountDownLatch(1);
    _async.createNode(latch);
    await(latch,CREATION_WAIT_IN_SECONDS,TimeUnit.SECONDS);
}
项目:curator-extensions    文件:Nodediscovery.java   
/**
 * Creates an instance of {@code ZooKeeperNodediscovery}.
 *
 * @param curator    Curator framework reference.
 * @param nodePath   The path in ZooKeeper to watch.
 * @param parser     The strategy to convert from ZooKeeper {@code byte[]} to {@code T}.
 */
public Nodediscovery(CuratorFramework curator,String nodePath,NodeDataParser<T> parser) {
    checkNotNull(curator);
    checkNotNull(nodePath);
    checkNotNull(parser);
    checkArgument(curator.getState() == CuratorFrameworkState.STARTED);
    checkArgument(!"".equals(nodePath));

    ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat(getClass().getSimpleName() + "(" + nodePath + ")-%d")
            .setDaemon(true)
            .build();

    _nodes = Maps.newConcurrentMap();
    _listeners = Sets.newSetFromMap(Maps.<NodeListener<T>,Boolean>newConcurrentMap());
    _curator = curator;
    _executor = Executors.newSingleThreadScheduledExecutor(threadFactory);
    _pathCache = new PathChildrenCache(curator,nodePath,false,_executor);
    _nodeDataParser = parser;
    _closed = false;
}
项目:Singularity    文件:StateManager.java   
public void save(SingularityHostState hostState) throws InterruptedException {
  final String path = ZKPaths.makePath(ROOT_PATH,data);
      }
    } catch (Throwable t) {
      throw Throwables.propagate(t);
    }
  }
}
项目:kiji-rest    文件:ManagedKijiClient.java   
/**
 * Check whether this KijiClient is healthy.
 *
 * @return health status of the KijiClient.
 */
public HealthCheck.Result checkHealth() {
  final State state = mState.get();
  Preconditions.checkState(state == State.STARTED,"Can not check health while in state %s.",state);
  List<String> issues = Lists.newArrayList();

  if (mZKFramework.getState() != CuratorFrameworkState.STARTED) {
    issues.add(String.format("ZooKeeper connection in unhealthy state %s.",mZKFramework.getState()));
  }

  for (KijiInstanceCache instanceCache : mInstanceCaches.asMap().values()) {
    issues.addAll(instanceCache.checkHealth());
  }
  if (issues.isEmpty()) {
    return HealthCheck.Result.healthy();
  } else {
    return HealthCheck.Result.unhealthy(Joiner.on('\n').join(issues));
  }
}
项目:rollout-java    文件:RolloutZKClient.java   
@Override
public void start() throws Exception {
    if (!isstarted.compareAndSet(false,true)) {
        throw new RuntimeException("Service already started!");
    }
    if (framework.getState() != CuratorFrameworkState.STARTED) {
        throw new RuntimeException("CuratorFramework is not started!");
    }
    nodeCache.getListenable().addListener(new NodeCacheListener() {
        @Override
        public void nodeChanged() throws Exception {
            build();
        }
    });
    nodeCache.start(true);
    build();
}
项目:fluo    文件:OracleServer.java   
public synchronized void stop() throws Exception {
  if (started) {

    server.stop();
    serverThread.join();

    if (gcTsTracker != null) {
      gcTsTracker.stop();
    }

    started = false;

    currentleader = null;
    if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) {
      pathChildrenCache.getListenable().removeListener(this);
      pathChildrenCache.close();
      leaderSelector.close();
      curatorFramework.getConnectionStateListenable().removeListener(this);
      curatorFramework.close();
    }
    log.info("Oracle server has been stopped.");
  }
}
项目:id_center    文件:ZkManager.java   
/**
 * 创建Zookeeper连接
 *
 * @throws InterruptedException
 * @throws UnsupportedEncodingException
 */
@postconstruct
public void connect() throws InterruptedException,UnsupportedEncodingException {
    client = CuratorFrameworkFactory.builder()
            .connectString(connectString)
            .retryPolicy(new ExponentialBackoffRetry(DEFAULT_BASE_SLEEP_TIME_MS,DEFAULT_MAX_RETRIES))
            .namespace(DEFAULT_NAMESPACE)
            .authorization(DEFAULT_ACL_SCHEME,DEFAULT_ACL_AUTH.getBytes(DEFAULT_CHARSET)) // 设置权限
            .aclProvider(new ACLProvider() { // 设置ACL规则
                @Override
                public List<ACL> getDefaultAcl() {
                    return DEFAULT_ACL_LIST;
                }

                @Override
                public List<ACL> getAclForPath(String path) {
                    return DEFAULT_ACL_LIST;
                }
            })
            .build();

    if (CuratorFrameworkState.STARTED != client.getState()) {
        client.start();
    }

    while (!client.blockUntilConnected(MAX_WAIT_SECONDS,TimeUnit.SECONDS)) {
        log.info("can not connect to zookeeper,retry again!!");
    }
}
项目:DBus    文件:AbstractEvent.java   
protected <T> T deserialize(String path,Class<T> clazz) throws Exception {
    T packet = null;
    CuratorFramework curator = CuratorContainer.getInstance().getCurator();
    if (curator.getState() == CuratorFrameworkState.STOPPED) {
        LOG.info("[control-event] CuratorFrameworkState:{}",clazz);
        }
    }
    return packet;
}
项目:DBus    文件:AbstractEvent.java   
protected void saveZk(String node,String packet) {
    try {
        CuratorFramework curator = CuratorContainer.getInstance().getCurator();
        if (curator.getState() == CuratorFrameworkState.STOPPED) {
            LOG.info("[control-event] CuratorFrameworkState:{}",CuratorFrameworkState.STOPPED.name());
        } else {
            curator.setData().forPath(node,packet.getBytes());
        }
    } catch (Exception e) {
        LOG.error("[control-event] 报错znode: " + node + ",数据包:" + packet + "失败!",e);
    }
}
项目:DBus    文件:EventContainer.java   
protected void saveZk(String node,String packet) {
    try {
        CuratorFramework curator = CuratorContainer.getInstance().getCurator();
        if (curator.getState() == CuratorFrameworkState.STOPPED) {
            LOG.info("[EventContainer] CuratorFrameworkState:{}",e);
    }
}
项目:idworker    文件:ZookeeperWorkerRegister.java   
/**
 * 关闭注册
 */
@Override
public synchronized void logout() {
    CuratorFramework client = (CuratorFramework) regCenter.getRawClient();
    if (client.getState() == CuratorFrameworkState.STARTED) {
        // 移除注册节点
        regCenter.remove(nodePath.getWorkerIdpath());
        // 关闭连接
        regCenter.close();
    }
}
项目:asura    文件:ConfigSubscriber.java   
/**
 * 初始化zk连接
 *
 * @author zhangshaobin
 * @created 2013-6-26 上午10:21:34
 */
private void init() {
    applicationName = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.CONfig_APPLICATION_NAME_KEY,5000).get();

    Transaction tran = Cat.newTransaction("Asura Configuration init",applicationName + "_" + zkConfigEnsemble);

    try {

        if (Check.NuNStr(zkConfigEnsemble)) {
            logger.warn("ZooKeeper configuration running in file mode,zk is not enabled since not configured");
            Cat.logError("zk is not enabled since not configured",new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started."));
            return;
        }

        client = createAndStartZKClient(zkConfigEnsemble,zkConfigConnTimeout);

        if (client.getState() != CuratorFrameworkState.STARTED) {
            throw new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started.");
        }

        tran.setStatus(Transaction.SUCCESS);
    } catch (Exception e) {
        logger.error("连接配置中心服务器超时,时间5000毫秒。",e);
        Cat.logError("asura configuration init exception",e);
        tran.setStatus(e);
        System.exit(1);
    } finally {
        tran.complete();
    }
    logger.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date()) + applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
    logger.info(applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
}
项目:storm-dynamic-spout    文件:CuratorHelper.java   
/**
 * Quick check to ensure that Curator has been started.
 */
private void ensureCuratorHasstarted() {
    // If our client isn't started yet
    if (CuratorFrameworkState.STARTED != curator.getState()) {
        // Lets start it!
        logger.debug("Curator not started,starting it Now!");
        curator.start();
    }
}
项目:redirector    文件:BaSEOfflineIntegrationTest.java   
void closeCurator() {
    if (curatorFramework.getState() == CuratorFrameworkState.STARTED) {
        log.info("Closing curator");
        curatorFramework.close();
    }
    dataStoreSupport.shutdown();
}
项目:redirector    文件:ZookeeperConnectorTestBase.java   
protected void setupClient() {
    client = mock(CuratorFramework.class);
    existsBuilder = mock(ExistsBuilder.class);
    pathCreator = mock(ZookeeperConnector.IPathCreator.class);
    stackCache = mock(IStacksCache.class);
    nodeCacheFactory = mock(INodeCacheFactory.class);
    pathChildrenCacheFactory = mock(IPathChildrenCacheFactory.class);

    when(client.checkExists()).thenReturn(existsBuilder);
    when(client.getState()).thenReturn(CuratorFrameworkState.STARTED);
}
项目:trellis-rosid    文件:TrellisUtilsTest.java   
@Test
public void testGetCurator() throws Exception {
    final TestingServer zk = new TestingServer(true);

    final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,Validators.newValidator(),Jackson.newObjectMapper(),"")
        .build(new File(getClass().getResource("/config1.yml").toURI()));

    config.getZookeeper().setEnsembleServers(zk.getConnectString());

    final CuratorFramework curator = TrellisUtils.getCuratorClient(config);
    assertEquals(CuratorFrameworkState.STARTED,curator.getState());
}
项目:zoomap    文件:ZooMapTest.java   
@Test
public void garbaged_map_should_close_curator_client() throws NamingException {
    withServer(srv -> {
        final CuratorFramework client = ZooMap.Periscope.client(ZooMap.newMap(srv.getConnectString()));
        System.gc();
        await().atMost(5,TimeUnit.SECONDS).until(client::getState,is(CuratorFrameworkState.STOPPED));
    });
}
项目:albedo-thrift    文件:ThriftServerAddressproviderZookeeper.java   
@Override
public void afterPropertiesSet() throws Exception {
    // 如果zk尚未启动,则启动
    if (zkClient.getState() == CuratorFrameworkState.LATENT) {
        zkClient.start();
    }
    buildpathChildrenCache(zkClient,getServicePath(),true);
    cachedpath.start(StartMode.POST_INITIALIZED_EVENT);
    countDownLatch.await();
}
项目:dmaap-framework    文件:KafkaConsumerCache.java   
/**
 * Getting the curator oject to start the zookeeper connection estabished
 * 
 * @param curator
 * @return curator object
 */
public static CuratorFramework getCuratorFramework(CuratorFramework curator) {
    if (curator.getState() == CuratorFrameworkState.LATENT) {
        curator.start();

        try {
            curator.blockUntilConnected();
        } catch (InterruptedException e) {
            // Ignore
            log.error("error while setting curator framework :" + e.getMessage());
        }
    }

    return curator;
}
项目:coco    文件:RegisterHolder.java   
public static CuratorFramework getClient(String registerUrl) {
    if (registerHolder == null) {
        synchronized (RegisterHolder.class) {
            if (registerHolder == null) {
                registerHolder = new RegisterHolder();
                curatorMap = Maps.newHashMap();
                lock = new reentrantlock();
            }
        }
    }
    CuratorFramework client = null;
    lock.lock();
    try {
        String tempurl = registerUrl.trim();
        if (!curatorMap.containsKey(tempurl)) {
            ZkClientFactory zookeeperClientFactory = new ZkClientFactory().setAllAndGetClientFactory(tempurl);
            client = zookeeperClientFactory.newCuratorFramework();
            CuratorFrameworkState state = client.getState();
            if (state != CuratorFrameworkState.STARTED) {
                client.start();
            }
            curatorMap.put(tempurl,client);
        } else {
            client = curatorMap.get(tempurl);
        }
    } finally {
        lock.unlock();
    }
    return client;
}
项目:pravega    文件:ClusterZKImpl.java   
public ClusterZKImpl(CuratorFramework zkClient,String clusterName) {
    this.client = zkClient;
    this.clusterName = clusterName;
    if (client.getState().equals(CuratorFrameworkState.LATENT)) {
        client.start();
    }
}
项目:Hvalspik    文件:ZookeeperContainerBuilderTest.java   
@Test
public void testStart() throws InterruptedException {
  String zookeeperConnectionString = zookeeper.format("%HOST%:%EPORT%",2181);
  RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
  CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString,retryPolicy);
  client.start();
  client.blockUntilConnected();
  assertthat(client.getState(),is(CuratorFrameworkState.STARTED));
  client.close();
}
项目:watchconf    文件:DynamicConfigZKAdapter.java   
public DynamicConfigZKAdapter(final Class<T> clazz,final String path,final CuratorFramework curatorFramework,Converter<T,byte[]> converter,changelistener<T> changelistener) throws Exception {
    super(clazz,converter,Optional.fromNullable(changelistener));
    Preconditions.checkNotNull(curatorFramework,"CuratorFramework cannot be null");
    Preconditions.checkArgument(curatorFramework.getState() == CuratorFrameworkState.STARTED,"CuratorFramework must be started");
    Preconditions.checkArgument(path != null && !path.isEmpty(),"path cannot be null or blank");

    this.curatorFramework = curatorFramework;
    this.path = path;
    this.nodeCache = new NodeCache(curatorFramework,path);
}

今天关于TeaFramework——ORM框架的实现的分享就到这里,希望大家有所收获,若想了解更多关于.Net Framework 4.7或仅.Net Framework 2.0上的Winforms是否兼容Mono?、Entity Framework框架 (一)、org.apache.curator.framework.CuratorFramework的实例源码、org.apache.curator.framework.imps.CuratorFrameworkState的实例源码等相关知识,可以在本站进行查询。

本文标签: