整合redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-reis</artifactId>
</dependency>
複製程式碼
#配置redis
spring.redis.host=192.168.243.129
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=bisnow
#配置cache
spring.cache.cache-names=c1
複製程式碼
@SpringBootApplication
@EnableCaching
public class RediscacheApplication {
複製程式碼
@Service
@CacheConfig(cacheNames = "c1")
public class UserService {
@Cacheable(key = "#id")
public User getUserById(Long id,String username){
System.out.println(id);
User user = new User();
user.setId(id);
return user;
}
@CacheEvict(allEntries = false,beforeInvocation = false)
public void deleteById(Long id){
}
@CachePut
public User updateById(Long id){
User user = new User();
user.setId(99L);
user.setUsername("李四");
return user;
}
}
複製程式碼
@RunWith(SpringRunner.class)
@SpringBootTest
public class RediscacheApplicationTests {
@Autowired
UserService userService;
@Test
public void test1(){
User userById = userService.getUserById(99L,"");
System.out.println("userbyid >>> 1:" +userById);
User userById2 = userService.getUserById(99L,"");
System.out.println("uuerbyid >>> 2:" + userById2);
}
@Test
public void test2(){
User userById1 = userService.getUserById(99L,"");
System.out.println("uuerbyid >>> 1:" + userById1);
userService.deleteById(99L);
User userById2 = userService.getUserById(99L,"");
System.out.println("uuerbyid >>> 2:" + userById2);
}
@Test
public void test3(){
User userById = userService.getUserById(99L,"");
System.out.println("userbyid >>> 1:" +userById);
userService.updateById(99L);
User userById2 = userService.getUserById(99L,"");
System.out.println("uuerbyid >>> 2:" + userById2);
}
}
複製程式碼