<bean>
<property value="${redis.pool.minIdle}" />
<property value="${redis.pool.maxIdle}" />
<property value="${redis.pool.maxWaitMillis}" />
</bean>
<bean
>
<property value="true"></property>
<property value="${redis.ip}" />
<property value="${redis.port}" />
<property value="${redis.password}" />
<property value="${redis.timeout}" />
<property value="${redis.default.db}"></property>
<constructor-arg ref="jedisPoolConfig" />
</bean>
<bean>
<property ref="jedisConnectionFactory" />
<property>
<bean
></bean>
</property>
<property>
<bean
></bean>
</property>
<property>
<bean
></bean>
</property>
<property>
<bean
></bean>
</property>
</bean>
</beans>
利用:
用注解注入Template,直接挪用就好了。
@Repository
public class RedisService {
@Autowired
StringRedisTemplate stringRedisTemplate;
public void add(String key, User user, Long time) {
Gson gson = new Gson();
stringRedisTemplate.opsForValue().set(key, gson.toJson(user), time, TimeUnit.MINUTES);
}
public void add(String key, List<User> users, Long time) {
Gson gson = new Gson();
String src = gson.toJson(users);
stringRedisTemplate.opsForValue().set(key, src, time, TimeUnit.MINUTES);
}
public User get(String key) {
String source = stringRedisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(source)) {
return new Gson().fromJson(source, User.class);
}
return null;
}
public List<User> getUserList(String key) {
String source = stringRedisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(source)) {
return new Gson().fromJson(source, new TypeToken<List<User>>() {
}.getType());
}
return null;
}
public void delete(String key) {
stringRedisTemplate.opsForValue().getOperations().delete(key);
}
}
���果是测试的话:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
RedisService redisService;
@Before
public void setUp() {
}
@Test
public void get() {
User user = new User();
user.setName("wangjianfeng");
user.setAge(22);
redisService.add("userByName:" + user.getName(), user, 10L);
List<User> list = new ArrayList<>();
list.add(user);
redisService.add("list", list, 10L);
User user1 = redisService.get("userByName:wangjianfeng");
Assert.notNull(user1, "user is null");
List<User> list2 = redisService.getUserList("list");
Assert.notNull(list2, "list is null");
}
}
SpringBoot利用Redis缓存:
Springboot提供了许多缓存打点器,好比:
SimpleCacheManager
EhCacheManager
CaffeineCacheManager
GuavaCacheManager
CompositeCacheManager
SpringData提供了缓存打点器:RedisCacheManager
在SpringBoot中,在措施进口,加上@EnableCaching注解自动化设置符合的打点器。
然后我们利用本身写代码设置的方法,修改RedisConfig添加@EnableCaching注解,并担任CachingCongigurerSupport
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
...
}
Linux公社的RSS地点:https://www.linuxidc.com/rssFeed.aspx