public class Book {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book(int id) {
super();
this.id = id;
}
public Book() {
super();
}
@Override
public String toString() {
return ""+id;
}
}
public class BookDao {
public Object executeSQL() {
System.out.println("此处调用了Dao方法。executeSQL");
List<Book> books = new ArrayList<Book>();
for (int i = 0; i < 3; i++) {
Book b = new Book(i);
books.add(b);
}
return books;
}
}
public class BookCache {
public static Cache<String, List<Book>> cache = CacheBuilder.newBuilder()
.expireAfterAccess(8, TimeUnit.SECONDS).maximumSize(10)
.build();
}
public static void main(String[] args) {
try {
System.out.println("第一次调用dao方法,正确状态:应该调用Dao里的方法");
List<Book> books = BookCache.cache.get("points",
new Callable<List<Book>>() {
@Override
public List<Book> call() {
BookDao dao = new BookDao();
List<Book> list = (List<Book>) dao.executeSQL();
if (null == list || list.size() <= 0) {
list = new ArrayList<Book>();
}
return list;
}
});
for (Book book : books) {
System.out.println(book);
}
System.out.println("第二次调用dao方法,正确状态:不调用Dao里的方法");
List<Book> books2 = BookCache.cache.get("points",
new Callable<List<Book>>() {
@Override
public List<Book> call() {
BookDao dao = new BookDao();
List<Book> list = (List<Book>) dao.executeSQL();
if (null == list || list.size() <= 0) {
list = new ArrayList<Book>();
}
return list;
}
});
for (Book book : books2) {
System.out.println(book);
}
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Thread.currentThread();
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("休息十秒后,第三次调用dao方法,正确状态:调用Dao里的方法");
List<Book> books = BookCache.cache.get("points",
new Callable<List<Book>>() {
@Override
public List<Book> call() {
BookDao dao = new BookDao();
List<Book> list = (List<Book>) dao.executeSQL();
if (null == list || list.size() <= 0) {
list = new ArrayList<Book>();
}
return list;
}
});
for (Book book : books) {
System.out.println(book);
}
System.out.println("第四次调用dao方法,正确状态:不调用Dao里的方法");
List<Book> books2 = BookCache.cache.get("points",
new Callable<List<Book>>() {
@Override
public List<Book> call() {
BookDao dao = new BookDao();
List<Book> list = (List<Book>) dao.executeSQL();
if (null == list || list.size() <= 0) {
list = new ArrayList<Book>();
}
return list;
}
});
for (Book book : books2) {
System.out.println(book);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
第一次调用dao方法,正确状态:应该调用Dao里的方法
此处调用了Dao方法。executeSQL
0
1
2
第二次调用dao方法,正确状态:不调用Dao里的方法
0
1
2
休息十秒后,第三次调用dao方法,正确状态:调用Dao里的方法
此处调用了Dao方法。executeSQL
0
1
2
第四次调用dao方法,正确状态:不调用Dao里的方法
0
1
2
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。