本帖最后由 wdx_827 于 2017-5-3 17:16 编辑
用springboot开发的应用,redis的配置类如下 @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {
@Bean public KeyGenerator KeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; }
@Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); }
@Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } } 实体类: public class User { private Long id; private String firstName; private String lastName;
public User() {
}
public User(Long id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } } 方法类:
@Service @CacheConfig(cacheNames = "userCache") public class UserService {
Map<Long, User> users=new HashMap<Long,User>();
@CachePut(key = "'user:'+#user.id") public User save(User user) { users.put(user.getId(),user); return user; } @Cacheable(key = "'user:'+#id") public User findById(final Long id) { System.out.println("无缓存的时候调用这里,id:" + id); return users.get(id); } }
在eclipse中将项目copy两份,分布启动调试。
启动两个调试进程,首先启动第一个进程测试方法中如下: private final static Long ID = 1L;@Test
public void testUser() throws Exception {
User user = new User(ID, "lin", "cheng");
userService.save(user);
User optional = userService.findById(ID);}
在第一个测试中发现userService.findById(ID);走的是缓存。
然后启动第二个进程测试方法如下 private final static Long ID = 1L;
@Test public void testUser() throws Exception {
User optional = userService.findById(ID);} 最后第二给进程中调用User optional = userService.findById(ID)发现没有走redis。请问为啥没走缓存啊?
|