@RequestMapping( value = {"/{user_name}/update"}, method = {RequestMethod.GET} ) public void update(@PathVariable String user_name, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { UserInfo userInfo = this.userInfoService.getUserInfo(user_name); response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); JSONObject jsonUserInfo = userInfo.getJsonObject(); out.println(jsonUserInfo.toString()); out.flush(); out.close(); }
时间: 2023-06-25 19:08:04 浏览: 138
这是一个使用Spring MVC框架的Java代码段,用于处理GET请求并返回用户信息的JSON对象。具体来说,它使用了@RequestMapping注释将URL映射到处理程序方法上,@PathVariable注释将URI模板变量映射到方法参数上,Model对象用于向视图层传递数据,HttpServletRequest和HttpServletResponse对象用于处理HTTP请求和响应,UserInfoService对象用于获取用户信息,JSONObject对象用于将用户信息转换为JSON格式,PrintWriter对象用于将JSON字符串写入HTTP响应中。
相关问题
springboot整合redis整合@Cacheable、@CachePut、@CacheEvict注解增删改查实例
好的,下面是一个使用Spring Boot整合Redis的`@Cacheable`、`@CachePut`、`@CacheEvict`注解实现增删改查的示例:
1. 添加Redis依赖
在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```
2. 配置Redis连接
在application.properties中添加以下配置:
```properties
# Redis连接配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
# 开启缓存
spring.cache.type=redis
```
3. 编写Redis配置类
```java
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.util.Arrays;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// key序列化方式
RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer); // key
redisTemplate.setHashKeySerializer(stringRedisSerializer); // hash key
// value序列化方式
RedisSerializer<Object> valueRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setValueSerializer(valueRedisSerializer); // value
redisTemplate.setHashValueSerializer(valueRedisSerializer); // hash value
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory);
return builder.build();
}
@Bean
public KeyGenerator wiselyKeyGenerator() {
return (Object target, Method method, Object... params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
Arrays.stream(params).forEach(param -> sb.append(param.toString()));
return sb.toString();
};
}
}
```
4. 编写实体类
```java
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
public User(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
```
5. 编写Service
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserDao userDao;
@Cacheable(value = "user", keyGenerator = "wiselyKeyGenerator")
public User getUserById(Integer id) {
return userDao.getUserById(id);
}
@CachePut(value = "user", keyGenerator = "wiselyKeyGenerator")
public User updateUser(User user) {
userDao.updateUser(user);
return user;
}
@CacheEvict(value = "user", keyGenerator = "wiselyKeyGenerator")
public void deleteUserById(Integer id) {
userDao.deleteUserById(id);
}
}
```
6. 编写Controller
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
return userService.getUserById(id);
}
@PutMapping("")
public User updateUser(@RequestBody User user) {
return userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUserById(@PathVariable Integer id) {
userService.deleteUserById(id);
}
}
```
7. 测试
启动应用后,可以通过以下方式测试:
- 获取用户:GET http://localhost:8080/user/1
- 更新用户:PUT http://localhost:8080/user
请求体:
```json
{
"id": 1,
"name": "Tom",
"age": 20
}
```
- 删除用户:DELETE http://localhost:8080/user/1
以上就是一个使用Spring Boot整合Redis的`@Cacheable`、`@CachePut`、`@CacheEvict`注解实现增删改查的示例。
解析接口:在应用启动时,Feign会扫描所有带有@FeignClient注解的接口,并将其解析成可执行的HTTP请求,生成动态代理对象并保存在Spring的ApplicationContext中。举个例子
比如我们有一个名为UserService的服务,它提供了一些RESTful API,我们想通过Feign来调用这些API。我们可以先定义一个接口,如下所示:
```java
@FeignClient(name = "user-service")
public interface UserFeignClient {
@RequestMapping(method = RequestMethod.GET, value = "/users/{userId}")
User getUser(@PathVariable("userId") String userId);
@RequestMapping(method = RequestMethod.POST, value = "/users")
User createUser(@RequestBody User user);
@RequestMapping(method = RequestMethod.PUT, value = "/users/{userId}")
User updateUser(@PathVariable("userId") String userId, @RequestBody User user);
@RequestMapping(method = RequestMethod.DELETE, value = "/users/{userId}")
void deleteUser(@PathVariable("userId") String userId);
}
```
上述代码中,@FeignClient注解指定了服务名为"user-service",Feign会根据这个服务名来发起HTTP请求。接口中的每个方法都对应一个HTTP请求,通过@RequestMapping注解指定请求的方法、路径、参数等信息。
接口定义好之后,我们就可以在代码中直接注入这个接口,并调用它的方法来发起HTTP请求,如下所示:
```java
@RestController
public class UserController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/users/{userId}")
public User getUser(@PathVariable String userId) {
return userFeignClient.getUser(userId);
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userFeignClient.createUser(user);
}
@PutMapping("/users/{userId}")
public User updateUser(@PathVariable String userId, @RequestBody User user) {
return userFeignClient.updateUser(userId, user);
}
@DeleteMapping("/users/{userId}")
public void deleteUser(@PathVariable String userId) {
userFeignClient.deleteUser(userId);
}
}
```
上述代码中,我们注入了UserFeignClient接口,并在方法中直接调用它的方法来发起HTTP请求。Feign会自动将接口中定义的参数和返回值转换成对应的HTTP请求和响应。
阅读全文