@configuration
public class evcacheconfig {
@bean
public evcacheclient evcacheclient() {
evcacheclient evcacheclient = new evcacheclient();
return evcacheclient;
}
}
编写 evcache service
上面几步完成之后,service的编写自然顺理成章,仅仅是一层封装而已
@service
public class evcacheservice {
@autowired
private evcacheclient evcacheclient;
public void setkey( string key, string value, int timetolive ) {
try {
evcacheclient.setkey( key, value, timetolive );
} catch (exception e) {
e.printstacktrace();
}
}
public string getkey( string key ) {
return evcacheclient.getkey( key );
}
}
编写测试 controller
我们编写一个方便用于测试的控制器,里面进行一系列对于缓存的 set 和 get,从而便于观察实验结果
@restcontroller
public class evcachetestcontroller {
@autowired
private evcacheservice evcacheservice;
@getmapping("/testevcache")
public void testevcache() {
try {
for ( int i = 0; i < 10; i++ ) {
string key = "key_" + i;
string value = "data_" + i;
int ttl = 180; // 此处将缓存设为三分钟(180s)生存期,时间一过,缓存即会失效
evcacheservice.setkey(key, value, ttl);
}
for (int i = 0; i < 10; i++) {
string key = "key_" + i;
string value = evcacheservice.getkey(key);
system.out.println("get of " + key + " returned " + value);
}
} catch (exception e) {
e.printstacktrace();
}
}
}
[root@localhost ~]# telnet 127.0.0.1 11211
trying 127.0.0.1...
connected to 127.0.0.1.
escape character is '^]'.
get key_0
value key_0 0 6
data_0
end
get key_1
value key_1 0 6
data_1
end
get key_2
value key_2 0 6
data_2
end
get key_3
value key_3 0 6
data_3
end
get key_4
value key_4 0 6
data_4
end
get key_5
value key_5 0 6
data_5
end
get key_6
value key_6 0 6
data_6
end
get key_7
value key_7 0 6
data_7
end
get key_8
value key_8 0 6
data_8
end
get key_9
value key_9 0 6
data_9
end